使用Child进行XML解析而不是值解析

使用Child进行XML解析而不是值解析

import java.io.File; import java.io.FileInputStream; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList; public class XPathEvaluator { /* * ServiceGroup serviceGroup = new ServiceGroup(); List * requiredServices = new ArrayList(); List * recommandedServices = new ArrayList(); Service service = new * Service(); */ public void evaluateDocument(File xmlDocument) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); String requiredServicesExpression = "/Envelope/Header"; InputSource requiredServicesInputSource = new InputSource( new FileInputStream(xmlDocument)); DTMNodeList requiredServicesNodes = (DTMNodeList) xPath.evaluate( requiredServicesExpression, requiredServicesInputSource, XPathConstants.NODESET); System.out.println(requiredServicesNodes.getLength()); NodeList requiredNodeList = (NodeList) requiredServicesNodes; for (int i = 0; i < requiredNodeList.getLength(); i++) { Node node = requiredNodeList.item(i); System.out.println(node.getChildNodes()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] argv) { XPathEvaluator evaluator = new XPathEvaluator(); File xmlDocument = new File("d://eva.xml"); evaluator.evaluateDocument(xmlDocument); } } 

我的xml正在关注此我尝试解析标题信息

    
08301 00000

我无法得到Header child我怎么能得到它们在getchildNodes方法上给我null。 我检查了很多解决方案,但得到任何东西。

这个相关问题的接受答案有一个使用xpath解析xml的好例子。

我调试了你的代码,并且getChildNodes调用实际上并没有返回null,但它有一个令人困惑的toString()

以下解析是使用DOM完成的,我希望这可以帮助您解决

 { try{ File file = new File("xmlfile"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(file); Element root = document.getDocumentElement(); root.normalize(); printNode(root, 0); } catch (Exception e) { } } public static void printNode(Node node, int depth) { if (node.getNodeType() == Node.TEXT_NODE) { System.out.printf("%s%n", node.getNodeValue()); } else { NamedNodeMap attributes = node.getAttributes(); if ((attributes == null) || (attributes.getLength() == 0)) { System.out.printf("%s%n", node.getNodeName()); } else { System.out.printf("%s ", node.getNodeName()); printAttributes(attributes); } } NodeList children = node.getChildNodes(); for(int i=0; i