如何在现有xml文件中插入新节点

时间:2015-09-22 11:35:11

标签: java xml parsing dom

Greatings! 我很有兴趣如何在xml中传递和插入新节点。例如,我们有

<UserCards>
   <UserCard userCardId="ADC">
      <userName>nameONE</userName>
      <userSurname>surnameONE</userSurname>
      <userAge>25</userAge>
      <userAdress>adressONE</userAdress>
      <userPhone>297718535</userPhone>
   </UserCard>
       <UserCard userCardId="AC6">
          <userName>nameTWO</userName>
          <userSurname>surnameTWO</userSurname>
          <userAge>17</userAge>
          <userAdress>adressTWO</userAdress>
          <userPhone>557778899</userPhone>
   </UserCard>
</UserCards>

我们需要解析它并找到一个用户手机&#39; == 557778899并插入此卡newNode并获取

</UserCard>
   <UserCard userCardId="AC6">
    <userName>nameTWO</userName>
    <userSurname>surnameTWO</userSurname>
    <userAge>17</userAge>
    <userAdress>adressTWO</userAdress>
    <userPhone>557778899</userPhone>
    <newNode>value</newNode>
</UserCard>

我试图这样做但没有得到任何东西

     File fXmlFile = new File("Test/UserCards.xml");
                DocumentBuilderFactory dbFactory =                    DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);

                doc.getDocumentElement().normalize();


                Element root = doc.getDocumentElement();

                NodeList nList = doc.getElementsByTagName("UserCard");

                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node node = nList.item(temp);

                    if (node.getNodeType() == Node.ELEMENT_NODE) {

                        Element eElement = (Element) node;
//here im trying to find userPhone == 557778899 
                        if (userPhone.equals(eElement.getElementsByTagName("userPhone").item(0).getTextContent())) {
    //this part does not work it was one of my try
                            NodeList nl = doc.getElementsByTagName("UserCards");
                            Element newNode= doc.createElement("newNode");
                            newNode.appendChild(doc.createTextNode("hello"));
                            eElement.appendChild(newNode);

1 个答案:

答案 0 :(得分:1)

首先,使用xpath查找您的节点。你在createElement的正确轨道上,但你可以使用setTextContent。这是一个完整的例子。另外,我打印你的XML - 因为我可以。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
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.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Example {

    public static void main(String... args) throws Exception {

        FileInputStream fileInputStream = new FileInputStream("UserCards.xml");
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document document = documentBuilder.parse(fileInputStream);

        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();

        Node node = (Node) xPath
                .evaluate("//UserCard[userPhone/text()='557778899']", document.getDocumentElement(), XPathConstants.NODE);

        Node newNode = node.appendChild(document.createElement("newNode"));
        newNode.setTextContent("value");

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

        transformer.transform(new DOMSource(document),
                new StreamResult(new OutputStreamWriter(new FileOutputStream("UserCards2.xml"), "UTF-8")));

    }

}