【问题标题】:HIERARCHY_REQUEST_ERR while trying to add elements to xml file in a for loopHIERARCHY_REQUEST_ERR 尝试在 for 循环中将元素添加到 xml 文件
【发布时间】:2013-07-25 17:00:51
【问题描述】:

正如标题所示,我正在尝试使用 for 循环将元素添加到 xml 文档。 我有一个名为names 的字符串ArrayList,我希望对其进行迭代,并为每个名称创建一个<user> 元素,其属性为name,并带有一个子<record>,其属性为id,@ 987654327@、dateproject

不幸的是,如果您在下面的代码中向下滚动到 createDoc() 方法,当我尝试调用 doc.appendChild(user) 时,我会收到以下错误:

Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. 
at org.apache.xerces.dom.CoreDocumentImpl.insertBefore(Unknown Source)
at org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)
at test.XMLwriter.createDoc(XMLwriter.java:131)
at test.XMLwriter.<init>(XMLwriter.java:116)
at test.TestRunner.main(TestRunner.java:33)

我在 stackoverflow 上查看了一些具有相同错误的问题,但它们似乎都发生在与我的完全不同的情况下。我最好的猜测是,这个错误与我试图在同一层级创建太多父元素有关。

代码如下:

public class XMLwriter {
private ArrayList<String> names;
private Document doc;
private Random rand;
private ArrayList<Element> users;

public XMLwriter() throws ParserConfigurationException, TransformerException{

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    doc = docBuilder.newDocument();

    rand = new Random();
    users = new ArrayList<Element>();
    names = new ArrayList<String>();

    names.add("Ralph Wiggum");names.add("Mr. Hanky");names.add("Bulbasaur");
    names.add("Tyroil Smoochie Wallace");names.add("Scooby Doo");names.add("Neville Longbottom");
    names.add("Jabba the Hutt");names.add("Silky Johnson");names.add("Master Chief");
    names.add("Frodo Baggins");names.add("Clayton Bigsby");names.add("John Snow");
    names.add("Eric Cartman");names.add("Leoz Maxwell Jilliumz");names.add("Aslan");

    createDoc();
    generateFile();

}

public void createDoc(){
    for(int k = 0; k < names.size(); k++)
    {
        users.add(doc.createElement("user"));
    }
    for (int x = 0; x < names.size(); x++){

        //create the elements
        Element record = doc.createElement("record");
        users.get(x).appendChild(record);
        doc.appendChild(users.get(x));//The line that is throwing the error

        //create the attributes
        Attr name = doc.createAttribute("name");
        Attr date = doc.createAttribute("date");
        Attr project = doc.createAttribute("project");
        Attr time = doc.createAttribute("time");
        Attr id = doc.createAttribute("id");

        //give all of the attributes values
        name.setValue(names.get(x));
        date.setValue(new Date().toString());
        project.setValue("Project" + (rand.nextDouble() * 1000));
        time.setValue("" + rand.nextInt(10));
        id.setValue("" + (rand.nextDouble() * 10000));

        //assign the attributes to the elements
        users.get(x).setAttributeNode(name);
        record.setAttributeNode(date);
        record.setAttributeNode(project);
        record.setAttributeNode(time);
        record.setAttributeNode(id);


    }
}

public void generateFile() throws TransformerException{
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("C:\\Users\\sweidenkopf\\workspace\\test\\testxml.xml"));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(source, result);
}

}

【问题讨论】:

    标签: java xml loops hierarchy


    【解决方案1】:

    我发现了这个问题的答案。方法如下:

    我创建了另一个名为 &lt;userList&gt; 的分层层,每次 for 循环迭代时,我都将新创建的 &lt;user&gt; 设为 &lt;userList&gt; 的子级。

    最后,超出了 for 循环的范围,我将 &lt;userList&gt; 作为整个 xml 文档的子元素。

    这是为感兴趣的人准备的新代码。您可以阅读 createDoc() 方法中的 cmets 以帮助澄清我上面解释的内容:

    public class XMLwriter {
    private ArrayList<String> names;
    private Document doc;
    private Random rand;
    private ArrayList<Element> users;
    
    public XMLwriter() throws ParserConfigurationException, TransformerException{
    
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        doc = docBuilder.newDocument();
    
        rand = new Random();
        users = new ArrayList<Element>();
        names = new ArrayList<String>();
    
        names.add("Ralph Wiggum");names.add("Mr. Hanky");names.add("Bulbasaur");
        names.add("Tyroil Smoochie Wallace");names.add("Scooby Doo");names.add("Neville Longbottom");
        names.add("Jabba the Hutt");names.add("Silky Johnson");names.add("Master Chief");
        names.add("Frodo Baggins");names.add("Clayton Bigsby");names.add("John Snow");
        names.add("Eric Cartman");names.add("Leoz Maxwell Jilliumz");names.add("Aslan");
    
        createDoc();
        generateFile();
    
    }
    
    public void createDoc(){
        Element userList = doc.createElement("userList");//here, I create a new, over-arching element.
        for(int k = 0; k < names.size(); k++)
        {
            users.add(doc.createElement("user"));
        }
        for (int x = 0; x < 2; x++){
    
            //create the elements
            Element record = doc.createElement("record");
            users.get(x).appendChild(record);
            userList.appendChild(users.get(x));//I make each of the <user> elements a child of the over-arching element
            //The line that was throwing the error
    
            //create the attributes
            Attr name = doc.createAttribute("name");
            Attr date = doc.createAttribute("date");
            Attr project = doc.createAttribute("project");
            Attr time = doc.createAttribute("time");
            Attr id = doc.createAttribute("id");
    
            //give all of the attributes values
            name.setValue(names.get(x));
            date.setValue(new Date().toString());
            project.setValue("Project" + (rand.nextDouble() * 1000));
            time.setValue("" + rand.nextInt(10));
            id.setValue("" + (rand.nextDouble() * 10000));
    
            //assign the attributes to the elements
            users.get(x).setAttributeNode(name);
            record.setAttributeNode(date);
            record.setAttributeNode(project);
            record.setAttributeNode(time);
            record.setAttributeNode(id);
    
    
        }
        doc.appendChild(userList);//note how I append this child outside of the for loop
    }
    
    public void generateFile() throws TransformerException{
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\Users\\sweidenkopf\\workspace\\test\\testxml.xml"));
    
        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-14
      • 2017-12-25
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 2016-08-25
      • 1970-01-01
      相关资源
      最近更新 更多