【发布时间】:2016-10-24 20:17:00
【问题描述】:
有问题...
我有一些带有根元素的 XML 文件,3 个具有相同名称和不同属性的元素,并且每个元素都有一些元素。
我想在 FX 可观察列表中拥有名为“id”的元素属性。 不知道该怎么办。
【问题讨论】:
-
了解 X-Path,这是一种从 xml 中选择不同节点的技术。
标签: java xml parsing javafx observablelist
有问题...
我有一些带有根元素的 XML 文件,3 个具有相同名称和不同属性的元素,并且每个元素都有一些元素。
我想在 FX 可观察列表中拥有名为“id”的元素属性。 不知道该怎么办。
【问题讨论】:
标签: java xml parsing javafx observablelist
由于您没有给我太多信息,我不得不用一些虚拟代码来解释它。
所以假设你有这个 XML:
<root id="0">
<sub1 id="1">
<hell1>hell1</hell1>
</sub1>
<sub2>
<hell2 id="2">hell2</hell2>
</sub2>
<sub3>sub3</sub3>
</root>
请注意,正如您所说,“id”属性位于不同的元素级别。
从这里我也建议你像 Heri 一样使用 xpath。
从 XML 中获取所有具有“id”属性的元素的最简单的 xpath 是:
//*[@id]
如果你不知道如何在 Java 中使用 XML 和 Xpath,你可以在这里查看:
How to read XML using XPath in Java
Which is the best library for XML parsing in java
如果我想从我的 XML 中获取所有“id”属性值,它看起来像这样:
// My Test-XML
final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<root id=\"0\">\n" +
"\t<sub1 id=\"1\">\n" +
"\t\t<hell1>hell1</hell1>\n" +
"\t</sub1>\n" +
"\t<sub2>\n" +
"\t\t<hell2 id=\"2\">hell2</hell2>\n" +
"\t</sub2>\n" +
"\t<sub3>sub3</sub3>\n" +
"</root>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Here you have to put your XML-Source (String, InputStream, File)
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
// The xpath from above
XPathExpression expr = xpath.compile("//*[@id]");
// Here you get the node-list of all elements with an attribute named "id"
NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
// run through all nodes
Node node = nodeList.item(i);
// fetch the values from the "id"-attribute
final String idValue = node.getAttributes().getNamedItem("id").getNodeValue();
// Do something awesome!!!
System.out.println(idValue);
}
我假设您知道如何将这些值放入您的可观察列表中。 :)
如果您还有其他问题,请随时提出。
PS:如果您向我展示您的 XML,我可以以更有效的方式帮助您。
【讨论】: