[英]Java get XML nodes
我想获得前两个服务作者的姓名。
我有以下 XML 示例:
<ServiceSchema:id>10</ServiceSchema:id>
<ServiceSchema:name>Service 10</ServiceSchema:name>
<ServiceSchema:authorInfos>
<ServiceSchema:authorInfo>
<ServiceSchema:id>1</ServiceSchema:id>
<ServiceSchema:name>Service Author 1</ServiceSchema:name>
<ServiceSchema:authorInfo>
<ServiceSchema:authorInfo>
<ServiceSchema:id>2</ServiceSchema:id>
<ServiceSchema:name>Service Author 2</ServiceSchema:name>
<ServiceSchema:authorInfo>
</ServiceSchema:authorInfos>
<ServiceSchema:requirements>
<ServiceSchema:requirement>
<ServiceSchema:id>1</ServiceSchema:id>
<ServiceSchema:name>Requirement 1</ServiceSchema:name>
<ServiceSchema:authorInfos>
<ServiceSchema:authorInfo>
<ServiceSchema:id>5</ServiceSchema:id>
<ServiceSchema:name> Requirement Author 5</ServiceSchema:name>
<ServiceSchema:authorInfo>
</ServiceSchema:authorInfos>
</ServiceSchema:requirement>
.....
我可以使用以下代码获取所有名称节点:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource inputSource = new InputSource(new ByteArrayInputStream (xml.getBytes("utf-8")));
Document xmldocument = db.parse(inputSource);
NodeList nodeList = xmldocument.getElementsByTagNameNS("*", "name");
但我不知道如何只获得外部作者的名字。
谢谢你。
更新:
我完全想做的是:我为不同的节点搜索不同的 xml 文件。 上面的 xml 文件只是一个例子。
例如:
searchElementsXml = new String[]{"name", "id", "version", "description", "keywords", "authorInfos.authorInfo.name", "status"};
我有一些字段可以出现很多值。 喜欢作者信息。
所以我需要类似的东西:
NodeList nodes = doc.getElementsByTagName("ServiceSchema:authorInfos:authorinfo:name");
有没有好的解决方案?
如果我正确理解了您想要什么,我建议您获取所有作者信息 (ServiceSchema:authorInfo),然后获取每个 authorInfo 的名称节点。
你的 XML 是否正确我看不到 ServiceSchema:authorInfo 标签正在关闭
你能更新你正在寻找的输出吗? 要获取作者信息,您可以使用以下代码 NodeList nodes = doc.getElementsByTagName("ServiceSchema:authorInfos");
她是详细的执行代码
File fXmlFile = new File("/Users/Downloads/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("ServiceSchema:authorInfos");
for (int temp = 0; temp < nodes.getLength(); temp++) {
Node nNode = nodes.item(temp);
System.out.println(" Current Author Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Author Info Name : " + eElement.getElementsByTagName("ServiceSchema:authorInfo").getLength());
}
}
我最终按照其他人的建议使用了 xpath。 效果很好-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.