【问题标题】:How to extract the content between 2 sibling nodes in an XML document using Java如何使用 Java 提取 XML 文档中 2 个兄弟节点之间的内容
【发布时间】:2011-05-10 12:50:09
【问题描述】:

示例 xml 文档:

<a>
    <b>...</b>
    xyz
    <c>...</c>
</a>

有没有办法使用 Java 代码(通过 DOM 解析)提取位于标签 bc 之间的内容 xyz

【问题讨论】:

  • 这是固定格式吗?
  • 请提出一个正确的问题。你有什么问题?

标签: java xml dom xml-parsing


【解决方案1】:

假设该元素引用标记“a”,如果您在“b”和“c”标记之前和之后有内容,那么下面的代码应该提取您想要的内容并且也可以工作

    NodeList content = element.getChildNodes();
    StringBuilder textContent = new StringBuilder();
    int cntLength = content.getLength();
    for ( int i = 0; i < cntLength; i++ ) {
        Node paramValue = content.item( i );
        short type = paramValue.getNodeType();
        if ( ( type == Node.TEXT_NODE ) || ( type == Node.CDATA_SECTION_NODE ) ) {
            textContent.append( ((CharacterData) paramValue).getData() );   //  Both Text and CDATASection nodes are SubType of CharacterData
        }
    }

【讨论】:

    【解决方案2】:

    遍历根元素的节点 (&lt;a&gt;)。在您的示例中,第二个节点(索引为 2,因为节点从 1 开始索引)将是文本节点。

    Document document = ...; // create org.w3c.dom.Document instance from XML
    document.getDocumentElement().getChildNodes().item(2).getTextContent();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      相关资源
      最近更新 更多