gpt4 book ai didi

java - 如何自己从 XML 文件构建 DOM 树,即不使用 DocumentBuilder.parse(xml)?

转载 作者:行者123 更新时间:2023-11-29 05:56:22 25 4
gpt4 key购买 nike

假设有一个简单的 XML 文件如下:

<a>
<b>hello</b>
<c>world</c>
</a>

我想创建一个 DOM 树,而不使用 Java 库提供的解析器(我确实想使用其他 API 和数据结构,例如 Element)。我有点熟悉词法分析(标记化)部分,但是如何使用标记来构建树?

树创建算法是我从数据结构类中学到的东西。问题是如何在 Java 库中使用给定的 DOM 框架?例如 ElementNodeDOM API,它们可以帮助将新节点插入 DOM 树。

有没有现成的例子可以借鉴?

最佳答案

DocumentBuilderFactory开始,创建一个 DocumentBuilder 并从中创建一个新的 Document 对象。从那里,Document 具有添加元素、属性等的方法,因此您可以使用这些方法生成文档。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//dbf.setNamespaceAware(true); //If you need namespace support turn this on, it is off by default

Document doc = dbf.newDocumentBuilder().newDocument();

//Add a root element
Element rootElement = doc.createElement("root");
doc.appendChild(rootElement);

Attr att = doc.createAttribute("my-attribute");
att.setValue("value");
rootElement.appendChild(att);

关于java - 如何自己从 XML 文件构建 DOM 树,即不使用 DocumentBuilder.parse(xml)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11964582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com