尝试在for循环中向xml文件添加元素时的HIERARCHY_REQUEST_ERR [英] HIERARCHY_REQUEST_ERR while trying to add elements to xml file in a for loop

查看:228
本文介绍了尝试在for循环中向xml文件添加元素时的HIERARCHY_REQUEST_ERR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我正在尝试使用for循环向xml doc添加元素。
我有一个名为 names 的字符串 ArrayList 我希望迭代,并为每个名称创建一个< user> 元素,其属性为 name ,且子元素为< record> 具有 id 时间日期项目

As the title suggests, I am trying to add elements to an xml doc using a for loop. I have an ArrayList of strings called names that I wish to iterate through, and for each name create a <user> element with attribute name and with a child <record> that has the attributes id, time, date, and project.

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

Unfortunately, if you scroll down in the code below to the createDoc() method, when I try to call doc.appendChild(user), I get the following error:

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上看了几个有相同错误的问题,但它们似乎都发生在完全不同的情况下尊重我的。我最好的猜测是,这个错误与我试图在同一层级创建太多父元素的事实有关,但我不确定,我几乎没有使用xml的经验。

I have looked at a few questions on stackoverflow that have the same error, but they all seem to have occurred under completely different circumstances with respect to mine. My best guess is that this error has to do with the fact that I am trying to create too many parent elements at the same hierarchical level, but I am not sure and I have almost no experience with xml at all.

以下是代码:

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);
}

}

我把这段代码写成概念证明,因为我最终必须实际执行类似的操作,在那里我将有一个对象列表,每个对象都必须通过将对象分成其组成部分来添加到xml文件中部件获取方法。

I wrote this code as sort of a proof of concept because I will eventually have to actually perform a similar operation, where I will have a list of objects, each of which I must add to an xml file by separating the object out into its constituent parts with get methods.

任何人都可以帮我解决此错误吗?

Can anyone help me resolve this error?

推荐答案

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

I discovered the answer to this problem. Here is how:

我创建了另一个名为的层次结构层< userList> 每次for循环迭代时,我使新创建的< user> 成为< userList> 的子项。

I created another hierarchical layer called <userList> Each time the for loop iterated, I made the newly created <user> a child of <userList>.

最后,超出了for循环的范围,我将< userList> 作为xml的子项整个文档。

Finally, beyond the scope of the for loop, I made the <userList> a child of the xml document as a whole.

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

Here is the new code for those interested. You can read the comments in the createDoc() method to help clarify what I explained above:

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);
}

}

这篇关于尝试在for循环中向xml文件添加元素时的HIERARCHY_REQUEST_ERR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆