首页 > 解决方案 > 如何将 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;
}

标签: javaxmlxpath

解决方案


这是返回 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;
    }

推荐阅读