当前位置: 首页 > 面试题库 >

如何在XML Java中更新节点值

司宏伯
2023-03-14
问题内容

我目前正在处理xml项目。到目前为止,我已经使用Dom
Parser成功地将xml链接到java类。我在下面提供了代码。我正在努力的是将开始日期的月份更新一个月,因此类似2/1 / 2013、3 / 1/2013
…的内容将相应地在xml文件中更改。我updateDate在底部有方法调用,但是当我调用它时,xml文件不会更新它的值。帮助将不胜感激

之前的* data.xml *

<?xml version="1.0" encoding="UTF-8">
<data>
    <username>hello123</username>
    <startdate>01/01/2011</startdate>
    <enddate>06/01/2013</enddate>
</data>

想要data.xml 之后

<?xml version="1.0" encoding="UTF-8">
<data>
    <username>hello123</username>
    <startdate>02/01/2011</startdate> <--- This will change 
    <enddate>06/01/2013</enddate>
</data>

main.java

public class main {

    public static void main(String[] args) {

        Calendar cal2 = null;

            String username = null;
            String startdate = null;
            String enddate = null;
            String date = null;
            String date_end = null;

            try {

                File data = new File("data.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(data);
                doc.getDocumentElement().normalize();
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);         
                    if (node.getNodeType() == Node.ELEMENT_NODE) {     
                        Element element = (Element) node;
                        username = getValue("username", element);
                        startdate = getValue("startdate", element);
                        enddate = getValue("enddate", element);
                    }
                }

                date = startdate;

                //end date
                Date date_end = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(enddate);
                Calendar end_date_cal = Calendar.getInstance();  
                end_date_cal.setTime(date_end);

                // initial date
                Date date_int = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(date);
                cal2 = Calendar.getInstance();  
                cal2.setTime(date_int);

                //call the method 
                updateDate(cal2);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File("data.xml"));
                transformer.transform(source, result);

                System.out.println("Update Successfully");

            }

        } catch (Exception ex) {    
            log.error(ex.getMessage());     
            ex.printStackTrace();         
        }
    }

    private static void updateDate(Calendar cal2){

        cal2.add(Calendar.MONTH, 1);

        //need to push it back to the calendar
    }


    private static String getValue(String tag, Element element) {  
        NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();   
        Node node = (Node) nodes.item(0);   
        return node.getNodeValue();   
    }

    private static void setValue(String tag, Element element , String input) {  
        NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();   
        Node node = (Node) nodes.item(0); 
        node.setTextContent(input);
    }

}

问题答案:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate ld = LocalDate.parse("2/1/2013", formatter);
System.out.println("From " + formatter.format(ld));
ld = ld.plusMonths(1);
System.out.println("To " + formatter.format(ld));

哪些印刷品

From 2/1/2013
To 3/1/2013

但是,您永远不要将值应用回XML文档。正如我在上一个问题中试图演示的那样,您需要更改textContent节点的…

node.setTextContent(formatter.format(ld))

这就是为什么我建议使用xPath而不是浏览文档内容的原因

例如…

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class UpdateXML {

    public static void main(String[] args) {

        try {
            DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
            DocumentBuilder b = f.newDocumentBuilder();
            Document doc = b.parse(new File("Data.xml"));

            XPath xPath = XPathFactory.newInstance().newXPath();
            Node startDateNode = (Node) xPath.compile("/data/startdate").evaluate(doc, XPathConstants.NODE);
            startDateNode.setTextContent(addMonthTo(startDateNode.getTextContent()));

            xPath = XPathFactory.newInstance().newXPath();
            Node endDateNode = (Node) xPath.compile("/data/enddate").evaluate(doc, XPathConstants.NODE);
            endDateNode.setTextContent(addMonthTo(endDateNode.getTextContent()));

            Transformer tf = TransformerFactory.newInstance().newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty(OutputKeys.METHOD, "xml");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            DOMSource domSource = new DOMSource(doc);
            StreamResult sr = new StreamResult(new File("AData.xml"));
            tf.transform(domSource, sr);
        } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | DOMException | TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException exp) {
            exp.printStackTrace();
        }
    }

    public static String addMonthTo(String value) {

        String patterns[] = {"M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy", "MM/dd/yyyy"};

        LocalDate ld = null;
        for (String pattern : patterns) {
            try {
                ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(pattern));
                break;
            } catch (DateTimeParseException exp) {
            }
        }

        if (ld == null) {
            throw new DateTimeParseException("Could not parse " + value + " with available patterns", value, -1);
        }

        ld = ld.plusMonths(1);
        return DateTimeFormatter.ofPattern("MM/dd/yyyy").format(ld);

    }

}

花了…

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
  <username>admin</username>
  <password>12345</password>
  <interval>1</interval>
  <timeout>90</timeout>
  <startdate>1/1/2013</startdate>
  <enddate>06/01/2013</enddate>
  <ttime>1110</ttime>
</data>

并输出…

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
  <username>admin</username>
  <password>12345</password>
  <interval>1</interval>
  <timeout>90</timeout>
  <startdate>02/01/2013</startdate>
  <enddate>07/01/2013</enddate>
  <ttime>1110</ttime>
</data>

我希望开始日期早6个月,然后结束日期

Java 8

String endDateValue = "07/01/2013";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate endDate = LocalDate.parse(endDateValue, formatter);
LocalDate startDate = endDate.minusMonths(6);

String startDateValue = formatter.format(startDate);

日历

我更喜欢Joda-Time,但是

String endDateValue = "07/01/2013";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date endDate = sdf.parse(endDateValue);

Calendar cal = Calendar.getInstance();
cal.setTime(endDate);
cal.add(Calendar.MONTH, -6);

Date startDate = cal.getTime();
String startDateVaue = sdf.format(startDate);


 类似资料:
  • 在SpringDataNeo44中,我们只有,但例如,当我的UserEntity的属性(电子邮件)更改时,我不知道如何更新该属性。 我也尝试使用neo4j模板,但使用现有节点id保存实体会导致下面的回滚。 如何更新节点或节点属性?

  • 我有这个密码 但是,如果要更新节点的值,该怎么办?我试着在箱子里做value=newValue,但似乎不被允许。 我的树/节点的结构:

  • firebase中我的数据库截图 这里我有一个叫做产品的节点。在那里,我有许多子节点。所有这些节点都有一个共同的值叫做产品库存。我需要更新产品内部所有节点的产品库存值。我如何在android Studio(Java)中做到这一点,因为我正在开发一个购物应用程序?需要帮助。 流程是:用户将产品添加到购物车。在购物车里,我有ordernow按钮。因此,当用户现在单击order时,应该从products

  • SyntaxError:无效输入“h”:预期为“I/I”(第10行,第28列(偏移量:346))“merge(p:primaryconsumer),其中p.name=svc.name” 我100%确信这些名称是唯一的,并且将与现有节点集中的唯一使用者名称相匹配(有待观察)。 当唯一节点属性匹配时,如何将现有属性添加到新数据中?(我希望获得唯一的ID,但我必须能够在匹配上执行新数据的更新)

  • 而这是我的主课,有没有其他方法做得更有效率?

  • 问题内容: 我创建了一个新的JsonNode 与此节点一起,然后如何在其中添加键值对,以便可以使用新值构造此新节点?我在http://www.cowtowncoder.com/blog/archives/2011/08/entry_460.html中阅读的内容涉及使用 但是,查看Jackson的JsonNode(v1.8)的API并没有显示任何此类方法。 问题答案: 这些方法在:除法中,大多数读取