java - 解析没有标记名的 xml

标签 java xml document w3c

我有一个xml文件

<Response>
<StatusCode>0</StatusCode>
<StatusDetail>OK</StatusDetail>
<AccountInfo> 
    <element1>value</element1>
    <element2>value</element2>
    <element3>value</element2>
    <elementN>value</elementN>   
</AccountInfo>
</Response>

我想解析我在 AccountInfo 中的元素,但我不知道元素标签名称。

现在我正在使用并拥有此代码进行测试,但将来我会在 AccountInfo 中收到更多元素,但我不知道有多少名称

String name="";
String balance="";
 Node accountInfo = document.getElementsByTagName("AccountInfo").item(0);

        if (accountInfo.getNodeType() == Node.ELEMENT_NODE){
            Element accountInfoElement = (Element) accountInfo;
            name = accountInfoElement.getElementsByTagName("Name").item(0).getTextContent();
            balance = accountInfoElement.getElementsByTagName("Balance").item(0).getTextContent();
        }

最佳答案

这里有 2 种方法可以做到:

Node accountInfo = document.getElementsByTagName("AccountInfo").item(0);
NodeList children = accountInfo.getChildNodes();

或者你可以做

XPath xPath = XPathFactory.newInstance().newXPath();
NodeList children = (NodeList) xPath.evaluate("//AccountInfo/*", document.getDocumentElement(), XPathConstants.NODESET);

一旦你有了你的NodeList,你就可以遍历它们。

for(int i=0;i<children.getLength();i++) {
    if(children.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element elem = (Element)children.item(i);
        // If your document is namespace aware use localName
        String localName = elem.getLocalName();
        // Tag name returns the localName and the namespace prefix
        String tagName= elem.getTagName();
        // do stuff with the children
    }
}

关于java - 解析没有标记名的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24446849/

相关文章:

java - 如何防止小数除法时精度损失?

javascript - 从 JSON 响应中删除 '@' 作为 String() 后,在 WSO2 序列中使用 setPeyloadJSON() 时收到错误

c# - 将 XML 数据放入 Windows 事件日志

java - 无法从 Lotus Notes 中的邮件获取 HTML 内容,即使在 setConvertMIME(false) 之后,getMIMEEntity() 也会返回 null

java - 递归方法调用在 kotlin 中会导致 StackOverFlowError,但在 java 中不会

java.lang.NoSuchMethodError ,构建过程已损坏

c++ - 我可以从mfc中的另一个文档访问一个文档的数据吗

solr - Solr文档带有子元素?

java - 是否有更多像 Apache James 这样的 java 邮件服务器?

java - 如何在旋转时保持应用程序的相同状态?