我正在为 android 创建一个应用程序,并且正在从在线 xml 文件中提取并解析标签属性的值。假设 xml 文件如下所示。
<a>
<b>
<c id="00001" time="1:00" day="Friday" name1="John" name2="Mary"></c>
<c id="00002" time="2:00" day="Monday" name1="Ed" name2="Kate"></c>
<c id="00003" time="3:00" day="Sunday" name1="Mary" name2="Ed"></c>
<c id="00004" time="4:00" day="Friday" name1="Kate" name2="John"></c>
</b>
</a>
该应用程序将有一个设定的名称(例如 John、Ed、Mary、Kate),我想提取该名称出现在哪一行以及该名称所在属性的标签属性值(例如名称1、名称2),名称将保持不变,但会根据星期改变行和属性。
我已经搜索了答案,发现我很可能会使用 XPath。谁能帮助我如何实现这一点?我的解析方法对使用 xpath 重要吗? DOM 还是 SAX?
提前致谢!
最佳答案
package documentation for javax.xml.xpath
给出了很好的介绍,但这里也有一些示例代码:
InputSource xml = new InputSource(new StringReader("<a>\n" +
"<b>\n" +
"<c id=\"00001\" time=\"1:00\" day=\"Friday\" name1=\"John\" name2=\"Mary\"></c>\n" +
"<c id=\"00002\" time=\"2:00\" day=\"Monday\" name1=\"Ed\" name2=\"Kate\"></c>\n" +
"<c id=\"00003\" time=\"3:00\" day=\"Sunday\" name1=\"Mary\" name2=\"Ed\"></c>\n" +
"<c id=\"00004\" time=\"4:00\" day=\"Friday\" name1=\"Kate\" name2=\"John\"></c>\n" +
"</b>\n" +
"</a>"));
所以没有 SAX,但任何 DOM InputSource
都可以。之后是:
String name = "John";
XPath xpath = XPathFactory.newInstance().newXPath();
// the String.format is just here so you can see the XPath expression more
// clearly without all the ".."+x+".." string concat, feel free to replace
String expr = String.format("//a/b/c[@name1='%s']", name);
Node c = (Node) xpath.evaluate(expr, xml, XPathConstants.NODE);
NamedNodeMap attribs = c.getAttributes();
String id = attribs.getNamedItem("id").getNodeValue();
String time = attribs.getNamedItem("time").getNodeValue();
// etc.
如果元素名称c
在整个文档中是唯一的,则可以将XPath表达式缩减为//c[@name1='%s']
。
如果您需要匹配 name1
和 name2
,请改用此节点测试:[@name1='%s' 或 @name2=' %s']
。在这种情况下,您可能还需要从 evaluate()
获取 NodeList
来处理多个匹配:
NodeList c = (NodeList) xpath.evaluate(expr, xml, XPathConstants.NODESET);
关于java - 根据 xml 中某个属性的值获取标签属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7476682/