【问题标题】:Parse xml without tagname解析没有标记名的 xml
【发布时间】:2014-08-18 06:28:58
【问题描述】:

我有一个 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();
        }

【问题讨论】:

  • 如果您不知道可能有哪些标签(以及它们的含义),您想如何以有意义的方式提取信息?
  • 您确定要动态显示吗?如果您有 n 个以动态方式解析的不同变量,则可能很难使用它们(例如,如果您使用某种算法来计算某个值)。这些值将(或多或少)在列表中表示。通常的方法是为一组特定的输入提供一个实现。还是您只想将值转储到数据库中?
  • This answer 可以帮助您入门。
  • 我想将此信息发送到其他模块,该模块可以在前端打印它。我的程序将与不同的提供商合作,他们有不同的信息...提供商列表非常大...超过 300

标签: java xml document w3c


【解决方案1】:

这里有 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
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多