如何使用DOM重新定位XML中的节点?

时间:2015-03-25 17:36:00

标签: java xml dom

所以我有这个应该放入xml文件的电影。

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse("D:\\College\\Java Eclipse\\tema5\\Movies\\Movies.xml");


  try {
    Element rootElement = doc.createElement("Movie");
    doc.appendChild(rootElement);

    // firstname elements
    Element id = doc.createElement("Id");
    id.appendChild(doc.createTextNode("3"));
    rootElement.appendChild(id);

    // lastname elements
    Element name = doc.createElement("Name");
    name.appendChild(doc.createTextNode("Movie 3"));
    rootElement.appendChild(name);

    // nickname elements
    Element category = doc.createElement("Category");
    category.appendChild(doc.createTextNode("Animation"));
    rootElement.appendChild(category);

    // salary elements
    Element releasedate = doc.createElement("ReleaseDate");
    releasedate.appendChild(doc.createTextNode("10-Jun-2012"));
    rootElement.appendChild(releasedate);


    Element rating = doc.createElement("Rating");
    rating.appendChild(doc.createTextNode("10"));
    rootElement.appendChild(rating);

    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("D:\\College\\Java Eclipse\\tema5\\Movies\\Movies.xml"));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);



  } catch (TransformerException tfe) {
    tfe.printStackTrace();

  }

问题是在我的xml文件中我已经有两部电影,当它试图将第三部电影设为成功时,但是在第四部电影中它已经死了。我认为这是因为节点,我想知道如何重新定位文件的最后一个到所以我可以放置更多的电影。这是第一次插入后的xml文档。

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Movie>  
<Movie>
    <Id>1</Id>
        <Name>Movie 1</Name>
    <Category>Action</Category>
    <ReleaseDate>22-JUN-2010</ReleaseDate>
    <Rating>9</Rating>
</Movie>
<Movie>
    <Id>2</Id>
    <Name>Movie 2</Name>
    <Category>Comedy</Category>
    <ReleaseDate>2-JUN-2011</ReleaseDate>
    <Rating>8</Rating>
</Movie>

</Movie>
<Movie>
<Id>3</Id>
<Name>Movie 3</Name>
<Category>Animation</Category>
<ReleaseDate>10-Jun-2012</ReleaseDate>
<Rating>10</Rating>
</Movie>

1 个答案:

答案 0 :(得分:0)

Element docRoot = doc.getDocumentElement();
Element rootElement = doc.createElement("Movie");
docRoot.appendChild(rootElement);

我建议将rootElement变量重命名为新Movie,因为它会产生误导。你只能在xml中有一个根元素,你可以通过doc.getDocumentElement()得到它。