如何通过属性值获取XML字符串

huangapple go评论84阅读模式
英文:

How to get an XML string by attribute value

问题

我正在尝试解析一个 XML 文件,以获取“流程图”中步骤的按步骤 ID 排列的内容,该 ID 是 steps 的子元素:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CATALOG>
  <FLOWCHART>
    <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>
    <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>
    </STEPS>
  </FLOWCHART>
</CATALOG>

我目前拥有的 Java 代码将打印出所有步骤、流程图代码和流程图描述,但是如何通过整数值请求特定的步骤?

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class Flowchart
{
    public static void main(String argv[])
    {
        try
        {
            // 创建文件类的构造函数并解析 XML 文件
            File file = new File("src/flowchart.xml");
            // 获取文档构建器的实例的工厂
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            // 创建一个解析指定 XML 文件的构建器的实例
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
            NodeList nodeList = doc.getElementsByTagName("FLOWCHART");
            // nodeList 不能迭代,因此我们使用 for 循环
            for (int itr = 0; itr < nodeList.getLength(); itr++)
            {
                Node node = nodeList.item(itr);
                System.out.println("\nNode Name: " + node.getNodeName());
                if (node.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element eElement = (Element) node;
                    System.out.println("Flowchart ID: "+ eElement.getElementsByTagName("PRIMARYCODE").item(0).getTextContent());
                    for (int i = 0; i < (eElement.getElementsByTagName("STEPS").getLength() + 1) ; i++)
                    {
                        System.out.println("Steps: "+ eElement.getElementsByTagName("STEP").item(i).getTextContent());
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
英文:

I am trying to parse an XML file to get a "flowchart" step by the step id which is a child element of steps:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;CATALOG&gt;
&lt;FLOWCHART&gt;
&lt;PRIMARYCODE&gt;FC1&lt;/PRIMARYCODE&gt;
&lt;NAME&gt;Flowchart 1&lt;/NAME&gt;
&lt;STEPS&gt;
&lt;STEP id=&quot;1&quot;&gt;was powered on.&lt;/STEP&gt;
&lt;STEP id=&quot;2&quot;&gt;was not connected with a connection plate.&lt;/STEP&gt;
&lt;/STEPS&gt;
&lt;/FLOWCHART&gt;
&lt;FLOWCHART&gt;
&lt;PRIMARYCODE&gt;FC2&lt;/PRIMARYCODE&gt;
&lt;NAME&gt;Flowchart2&lt;/NAME&gt;
&lt;STEPS&gt;
&lt;STEP id=&quot;1&quot;&gt;was not powered on.&lt;/STEP&gt;
&lt;STEP id=&quot;2&quot;&gt;was connected with a connection plate.&lt;/STEP&gt;
&lt;/STEPS&gt;
&lt;/FLOWCHART&gt;
&lt;/CATALOG&gt;

The Java Code that I have thus far will print all the steps and the flowchart code, and flowchart description but how to I request a specific step by an integer value?

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class Flowchart
{
public static void main(String argv[])
{
try
{
//creating a constructor of file class and parsing an XML file
File file = new File(&quot;src/flowchart.xml&quot;);
//an instance of factory that gives a document builder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//an instance of builder to parse the specified xml file
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println(&quot;Root element: &quot; + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName(&quot;FLOWCHART&quot;);
// nodeList is not iterable, so we are using for loop
for (int itr = 0; itr &lt; nodeList.getLength(); itr++)
{
Node node = nodeList.item(itr);
System.out.println(&quot;\nNode Name: &quot; + node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
System.out.println(&quot;Flowchart ID: &quot;+ eElement.getElementsByTagName(&quot;PRIMARYCODE&quot;).item(0).getTextContent());
for (int i = 0; i &lt; (eElement.getElementsByTagName(&quot;STEPS&quot;).getLength() + 1) ; i++)
{
System.out.println(&quot;Steps: &quot;+ eElement.getElementsByTagName(&quot;STEP&quot;).item(i).getTextContent());
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

答案1

得分: 1

为了实现这一目的,使用XPath API会更加方便:

import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

public static String getStep(Document doc, String flowchartName, int stepId) throws XPathExpressionException {
    XPathFactory xpf = XPathFactory.newInstance();
    XPathExpression xpath = xpf.newXPath().compile("/CATALOG/FLOWCHART[NAME='" 
            + flowchartName 
            + "']/STEPS/STEP[@id='" 
            + stepId 
            + "']");
    return xpath.evaluate(doc);
}
英文:

For this purpose much more convenient would be usage of XPath API:

import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
public static String getStep(Document doc, String flowchartName, int stepId) throws XPathExpressionException {
XPathFactory xpf = XPathFactory.newInstance();
XPathExpression xpath = xpf.newXPath().compile(&quot;/CATALOG/FLOWCHART[NAME=&#39;&quot; 
+ flowchartName 
+ &quot;&#39;]/STEPS/STEP[@id=&#39;&quot; 
+ stepId 
+ &quot;&#39;]&quot;);
return xpath.evaluate(doc);
}

huangapple
  • 本文由 发表于 2020年10月1日 09:24:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64147874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定