如何将XML属性填充到String(最好是Observable List)中



这是XML代码:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CATALOG>
<FLOWCHART id="FC1">
<PRIMARYCODE>FC1</PRIMARYCODE>
<NAME>Flowchart 1</NAME>
<STEPS>
<STEP id="1">was powered on.</STEP>
<STEP id="2">was not connected with a connection plate.</STEP>
</STEPS>
</FLOWCHART>
<FLOWCHART id = "FC2">
<PRIMARYCODE>FC2</PRIMARYCODE>
<NAME>Flowchart2</NAME>
<STEPS>
<STEP id="1">was not powered on.</STEP>
<STEP id="2">was connected with a connection plate.</STEP>
<STEP id="3">Driver was not installed.</STEP>
<STEP id="4">Software was installed.</STEP>
</STEPS>
</FLOWCHART>
</CATALOG>

以下是我创建的方法,用于尝试填充流程图的id属性。我本质上是在尝试在Choicebox中填充这些选项。

public static String[] flowChartList(Document doc) throws XPathExpressionException {
XPathFactory xpf = XPathFactory.newInstance();
XPathExpression xpath = xpf.newXPath().compile("/CATALOG/FLOWCHART");
NodeList nodeList = (NodeList) xpath.evaluate(doc, XPathConstants.NODE);
String[] flowcharts = new String[nodeList.getLength()];
for (int index = 0; index < nodeList.getLength(); index++) {
Node nNode = nodeList.item(index);
Element eElement = (Element) nNode;
flowcharts[index] = eElement.getAttribute("id");
System.out.println("Found flowchart "+ flowcharts[index]);
}
return flowcharts;
}

这是返回ID列表的版本:

public static List<String> flowChartList(Document doc) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPathExpression xpath = xpf.newXPath().compile("/CATALOG/FLOWCHART");
NodeList nodeList = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
List<String> flowcharts = new ArrayList<>();
for (int index = 0; index < nodeList.getLength(); index++) {
Node nNode = nodeList.item(index);
Element eElement = (Element) nNode;
flowcharts.add(eElement.getAttribute("id"));
}
return flowcharts;
}

请注意使用XPathConstants.NODESET而不是XPathConstantis.NODE.

略微修改了直接在XPath:中获取id属性的版本

public static List<String> flowChartList(Document doc) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPathExpression xpath = xpf.newXPath().compile("/CATALOG/FLOWCHART/@id");
List<String> result = new ArrayList<>();
NodeList ns = (NodeList)xpath.evaluate(doc, XPathConstants.NODESET);
for(int i = 0; i < ns.getLength(); i++ ){
result.add(ns.item(i).getTextContent());
}
return result;
}

最新更新