java - 如何将 XML 属性填充到字符串(最好是可观察列表)
问题描述
这是 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 属性的方法。我实际上是在尝试在选择框中填充这些选项。
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 而不是 XPathConstants.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;
}
推荐阅读
- java - DynamicJasper:使用带有图像的交叉表
- python - 根据条件聚合数据框行
- angular - Prefix 将来自后端的 URL 标记为路由器可导航内部 URL 的最佳实践
- apache-spark - java.lang.NoClassDefFoundError:scala eclipse中的org/apache/spark/sql/SparkSession
- internationalization - spring-boot-starter-webflux 不能使用 AcceptHeaderLocaleResolver
- android - 特定 Android 设备上的输出显示不同
- r - 如何使用ggplot2绘制两个相邻的geom_tile,以便它们像热图中一样对齐?
- reactjs - 根据 React JS 中的状态变化改变元素的可见性
- bash - 如何从 tmux 外部查看 tmux 会话/窗口的预览?
- batch-file - EC2 Windows 用户数据:脚本未按预期运行