尝试在 for 循环中将元素添加到 xml 文件时出现 HIERARCHY_REQUEST_ERR

2023-12-24

正如标题所示,我尝试使用 for 循环将元素添加到 xml 文档中。 我有一个ArrayList称为的字符串names我希望迭代,并为每个名称创建一个<user>具有属性的元素name和一个孩子<record>具有以下属性id, time, date, and project.

不幸的是,如果您在下面的代码中向下滚动到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);
}

}


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

我创建了另一个名为<userList>每次 for 循环迭代时,我都会创建新创建的<user>的孩子<userList>.

最后,超出了 for 循环的范围,我做了<userList>整个 xml 文档的子级。

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

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

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试在 for 循环中将元素添加到 xml 文件时出现 HIERARCHY_REQUEST_ERR 的相关文章

随机推荐

  • 带有子菜单的可检查菜单项

    WPF 中是否可以将顶级子菜单设置为复选框 我似乎无法让它发挥作用
  • 来自具有交互作用的多元回归 glm 的 LC50 / LD50 置信区间

    我有一个准二项式 glm 其中有两个连续解释变量 假设 LogPesticide 和 LogFood 和交互作用 我想计算不同食物量 例如最小和最大食物值 下农药的 LC50 和置信区间 如何才能实现这一目标 示例 首先我生成一个数据集 m
  • Rails 的即时通讯实现?

    我花了一些时间研究几种技术来为 ruby on Rails 应用程序构建一个简单的即时消息系统 这看起来非常复杂 因为我还没有找到任何跨浏览器的实现或任何 1 1 概念证明 调查 xmpp客户端 github上有Candy只支持群聊 xmp
  • 存储库层是否应该返回数据传输对象(DTO)?

    我有一个存储库层负责我的数据访问 它由服务层调用 服务层返回经过序列化并通过线路发送的 DTO 通常 服务只是访问存储库并返回存储库返回的任何内容 但要使其发挥作用 存储库必须返回该 DTO 的实例 否则 您首先必须将存储库返回的数据层对象
  • Android:选择器中禁用按钮的文本颜色未显示?

    我正在尝试制作一个带有选择器的按钮 我的按钮可以具有以下状态 启用 禁用 按下 未按下 根据上述状态 我需要操纵按钮 文字颜色 背景图 该按钮从我被禁用开始 因此它应该具有禁用的 textColor 和禁用的按钮背景 但我可以看到默认的文本
  • jQuery Mobile 弹出窗口未在 .popup('open') 上打开

    我正在尝试使用 jQuery Mobile 1 3 1 的弹出窗口在登录凭据错误时警告用户 我从 jquerymobile 文档中的基本模板开始 但我无法让它与 popupBasic popup open 如果我这样使用它 div div
  • 如何在加特林的Json Body中添加随机值?

    我需要每次创建一个随机正整数并将其发送到加特林中的 Json 主体 我使用下面的代码创建一个随机正整数 val r new scala util Random val OrderRef r nextInt Integer MAX VALUE
  • 为什么在套索回归中计算 MSE 会给出不同的输出?

    我正在尝试对 lasso2 包中的前列腺癌数据运行不同的回归模型 当我使用 Lasso 时 我看到两种不同的方法来计算均方误差 但它们确实给了我完全不同的结果 所以我想知道我是否做错了什么 或者这是否仅仅意味着一种方法比另一种方法更好 Ne
  • 启用 httpd-vhosts.conf 后 WAMP 服务器未运行

    我尝试在 WAMP 安装上启用虚拟主机 但如果启用 http vhosts conf WAMP 服务器将不会运行 并且图标保持橙色 这是我的主机文件 127 0 0 1 localhost 127 0 0 1 test localhost
  • 关系方法必须从 Laravel 4 中未查看的模型调用返回 Illuminate\Database\Eloquent\Relations\Relation 类型的对象

    我有一个模型Ability 它属于另一个模型AbilityType
  • iOS 开发者企业计划会员资格到期前续订

    我收到了苹果公司发来的关于企业会员计划续订的电子邮件 以下是我的相关问题 计划到期前续订对分发证书有影响吗 如果在到期前续订程序 使用分发证书签名的应用程序是否可以继续运行而不会出现任何问题 续订后到期前是否需要再次分发企业应用程序 感谢您
  • 从命令行对不同长度的十六进制数进行排序?

    如果我有一个不同长度的十六进制数文件 例如 1F b c 如何从命令行对它们进行排序 欢迎使用 Linux 解决方案 尽管我将使用 Windows 和 cygwin 或 gnuwin32 注意 我显然不能使用 SORT 因为这会使它们保持错
  • 在Windows中,有没有办法将errno转换为HRESULT?

    我知道HRESULT FROM WIN32宏将 Win32 错误代码转换为 HRESULT 有什么方法可以从errno error 简而言之 不 As of http msdn microsoft com en us library 581
  • Raphael:通过简单的无限动画逐渐减慢动画速度

    这个问题在本质上与两年前提出的另一个问题类似 为什么 Raphael 的帧速率在这段代码上变慢了 https stackoverflow com questions 2733613 why does raphaels framerate s
  • MySQL - 查询所有没有预约的用户

    如果我有两个表 用户和约会 我将如何查询数据库以找到类似以下内容的内容 SELECT FROM users WHERE none of appointments user user id 我假设我需要某种类型的约会表连接 只是不知道从哪里开
  • Apache 缓存 javascript 资源?

    不久前我在使用 javascript 资源时遇到了麻烦 当我对它们进行更改时 它们不会生效 文件将变成无效的 javascript 萤火虫抛出错误和警告 我注意到我的更改没有出现 并且特殊字符被添加到文件末尾 再进一步挖掘 我注意到特殊字符
  • JavaScript 圆角透明背景

    我正在寻找一个可以在上面创建圆角的 JavaScript 库div具有透明背景的标签 使得父元素的背景颜色 图像在圆角处可见 以圆角为例without透明背景 看看左边的菜单这一页 http chaletsdesbouleaux com 请
  • Angular UI-Router 将根 url 发送到 404

    我有一个令人恼火的问题ui router 一切都按我想要的方式进行 所有错误的 URL 都会发送到404状态 但是 即使当 url 为时我的默认状态正确呈现 网址为 被重定向到 404 我怎样才能提供服务default向双方声明 and a
  • 更改 jquerymobile 上的自定义导航栏图标

    尚未找到更改具有多个页脚的页面上的自定义导航栏图标的解决方案 这就是我目前正在使用的 live menu ui icon css background url btn on gif important live menu ui icon c
  • 尝试在 for 循环中将元素添加到 xml 文件时出现 HIERARCHY_REQUEST_ERR

    正如标题所示 我尝试使用 for 循环将元素添加到 xml 文档中 我有一个ArrayList称为的字符串names我希望迭代 并为每个名称创建一个