如何获得Node& Java中XML中的节点值 [英] how to get Node & node values from XML in java

查看:351
本文介绍了如何获得Node& Java中XML中的节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml试图解析&阅读它,但不知道xml可以包含多少个节点?因此,我正在尝试读取节点&节点值?

I have an xml trying to parse & read it, but dont know how many nodes the xml may contain? So I am trying to read the node & node values ?

我怎么说?

<company>
    <personNam>John</personName>
    <emailId>abc@test.com</emaiId>
    <department>Products</department>
    (may have additionaly nodes & values for same)
</company>

对不起,忘记使用Dom添加我的代码了:-

Sorry forgot to add my code, using Dom:-

Document document = getDocumentBuilder().parse(new ByteArrayInputStream(myXML.getBytes("UTF-8")));          
String xPathExp = "//company";
XPath xPath = getXPath();
NodeList nodeList = (NodeList)xPath.evaluate(xPathExp, document, XPathConstants.NODESET);           
nodeListSize = nodeList.getLength();
System.out.println("#####nodeListSize"+nodeListSize);

for(int i=0;i<nodeListSize;i++){
    element=(Element)nodeList.item(i);
    m1XMLOutputResponse=element.getTextContent();
    System.out.println("#####"+element.getTagName()+"   "+element.getTextContent());
}


推荐答案

请考虑使用 JAXB 库。这确实是将XML映射到Java类以及从Java类映射回来的一种轻松的方法。基本原理是JAXB会采用您的XML模式(XSD)并为您生成相应的Java类。然后,您只需调用 marshall unmarshall 方法即可,这些方法使用XML的内容填充Java类,或生成XML

Consider using the JAXB library. It's really a painless way of mapping your XML to Java classes and back. The basic principle is that JAXB takes your XML Schemas (XSD) and generates corresponding Java classes for you. Then you just call marshall or unmarshall methods which populate your Java class with the contents of the XML, or generates the XML from your Java class.

当然,唯一的缺点是您需要知道如何编写XML模式:)

The only drawback is, of course, that you'd need to know how to write the XML Schemas :)

这篇关于如何获得Node&amp; Java中XML中的节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆