如何使用 Java XML 解析器从 XML 获取节点属性值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17404728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the node attribute values from XML using Java XML parser?
提问by Sahal
<Files>
<File Name="D:/temp/OpId_63_7b126c8d-f90a-402b-9902-786c7995314f/35f9cdf8-f6cc-4c9d-b0e5-cc21c1842765" />
<File Name="D:/temp/PPPPOpId_63_7b126c8d-f90a-402b-9902-786c7995314f/35f9cdf8-f6cc-4c9d-b0e5-cc21c1842765" />
</Files>
From the above XML I want two file names like this:
从上面的 XML 我想要两个这样的文件名:
D:/temp/OpId_63_7b126c8d-f90a-402b-9902-786c7995314f/35f9cdf8-f6cc-4c9d-b0e5-cc21c1842765
D:/temp/PPPPOpId_63_7b126c8d-f90a-402b-9902-786c7995314f/35f9cdf8-f6cc-4c9d-b0e5-cc21c1842765
回答by James Holderness
Using javax, you could extract the data via xpath queries with something like this:
使用javax,您可以通过 xpath 查询提取数据,如下所示:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(stream);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String name1 = (String)xpath.evaluate("/Files/File[1]/@Name", doc, XPathConstants.STRING);
String name2 = (String)xpath.evaluate("/Files/File[2]/@Name", doc, XPathConstants.STRING);
This is assuming your XML is loading from an inputstream in the streamvariable. If you already have the XML as a string, you could convert that to a stream like this:
这是假设您的 XML 从流变量中的输入流加载。如果您已经将 XML 作为字符串,则可以将其转换为这样的流:
InputStream stream = new ByteArrayInputStream(xmlstring.getBytes("UTF-8"));
You could also load the XML directory from a url with:
您还可以使用以下网址从 url 加载 XML 目录:
Document doc = docBuilder.parse(url);
Note that you'll need at least these imports:
请注意,您至少需要这些导入:
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
回答by Milindu Sanoj Kumarage
using DOM XML parser
使用 DOM XML 解析器
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;
then,
然后,
File filesXML = new File("/files.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(filesXML);
NodeList nList = doc.getElementsByTagName("File");
for (int i= 0; i< nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("File: " + eElement.getAttribute("Name"));
}
}
回答by membersound
If you're just doing that simple stuff, have a look at any Java XML parsing reference.
如果您只是在做那些简单的事情,请查看任何 Java XML 解析参考。
For a good XML Parser take JAXB
with something like this (untested):
对于一个好的 XML Parser 来说JAXB
,像这样(未经测试):
@XmlRootElement(name="Files")
public class FilesXML {
@XmlElementWrapper(name="File")
@XmlAttribute(name="Name")
private String filename;
}
Then marshall and unmarshall as you like.
然后根据需要编组和解组。
回答by Harshavardhan Konakanchi
DocumentBuilderFactory docbuilderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docbuilder = docbuilderfactory.newDocumentBuilder();
Document document = docbuilder.parse(fileName);
String xpath = "//File";
NodeList testConfig = org.apache.xpath.XPathAPI.selectNodeList(document, xpath);
count = testConfig.getLength();
String fileNames[] = new String[count];
int rows = 0;
while (rows < count) {
Node row = testConfig.item(rows);
if (row.getNodeType() == Node.ELEMENT_NODE) {
AttributeMap map = (AttributeMap) row.getAttributes();
int attrCount = map.getLength();
int j = 0;
Properties props = new Properties();
while (j < attrCount) {
props.put(map.item(j).getNodeName(),map.item(j).getNodeValue().trim());
j++;
}
fileNames[rows] = props.getProperty("Name"); // Maniuplate The props object
}
rows++;
}
As per the above code, the array object, fileNames has the all the file names available in the xml file
根据上面的代码,数组对象 fileNames 具有 xml 文件中可用的所有文件名