gpt4 book ai didi

java - 如何在 Java 中解析 XML 元素根并选择它的某些值?

转载 作者:行者123 更新时间:2023-11-30 05:57:59 24 4
gpt4 key购买 nike

我正在寻找一种实用的方法来解析 xml 根元素并从中获取一些值。我尝试了很多方法,但没有一个有效。

       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

Document doc = factory.newDocumentBuilder().parse(fileLoaded);

Element root = null;

NodeList list = doc.getChildNodes();
System.out.println(list.toString());
for (int i = 0; i < list.getLength(); i++) {
if (list.item(i) instanceof Element) {
root = (Element) list.item(i);
System.out.println(root.toString());
break;
}
}
root = doc.getDocumentElement();
}

XML 文件:

    <planes_for_sale id="planeId" num="1452" name="boing">
<ad>
<year> 1977 </year>
<make> test </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
<description> New paint, nearly new interior,
685 hours SMOH, full IFR King avionics </description>
<price> 23,495 </price>
<seller phone = "555-222-3333"> Skyway Aircraft </seller>
<location>
<city> Rapid City, </city>
<state> South Dakota </state>
</location>

就我而言,我想从 planes_for_sale 根元素加载 idnumname

最佳答案

使用 XPath 提取属性值和元素内容。

    DocumentBuilder builder = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder();

Document doc = builder.parse(...);

XPath xp = XPathFactory
.newInstance()
.newXPath();

String id = xp.evaluate("planes_for_sale/@id", doc);
String num = xp.evaluate("planes_for_sale/@num", doc);
String name = xp.evaluate("planes_for_sale/@name", doc);

System.out.println("id: " + id);
System.out.println("num: " + num);
System.out.println("name: " + name);

产品:

id: planeId
num: 1452
name: boing

关于java - 如何在 Java 中解析 XML 元素根并选择它的某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52823324/

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