当我的 XML 标签中包含“_”时,无法从文档中检索节点列表

Not able to retrieve Node List from Document when my XML tag contains "_" in it

我有一个xml这样的

<PARENT>
<TAG_1>
<ROLE>Architect </ROLE>
</TAG_1>
<TAG2>
<ROLE>Architect </ROLE>
</TAG2>
</PARENT>

我正在使用 JAX-B 框架进行编组和取消编组。

问题是在我检索 org.w3c.dom.NodeList 时,我可以为不包含 _ 的 TAG2 做,而不能为包含 _(下划线)的 TAG1 做

org.w3c.dom.NodeList nodeList = org.w3c.dom.Document.getElementsByTagName("TAG2") returns 我的长度 1 是正确的。

org.w3c.dom.NodeList nodeList = org.w3c.dom.Document.getElementsByTagName("TAG_1") ,它 returns 我的长度是 0 但它应该是 1 。

任何人都可以建议下划线可能有什么问题以及如何处理它,因为XML我无法按照客户给出的方式进行更改。

谢谢

嗯,对我有用:

package com.stackof.helps.nonspring;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * @author samuele m.
 *
 */
public class MixedTest
{
    @Test
    public void testPathItem() throws Exception {
        String xml = "<PARENT><TAG_1><ROLE>Architect </ROLE></TAG_1><TAG1><ROLE>Engineer </ROLE></TAG1></PARENT>";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setIgnoringComments(true);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        Document doc = dBuilder.parse(is);
        NodeList nodeList1 = doc.getElementsByTagName("TAG1");
        NodeList nodeList2 = doc.getElementsByTagName("TAG_1");
        Assert.assertEquals(1, nodeList1.getLength());
        Assert.assertEquals(1, nodeList2.getLength());

        NodeList engList = ((Element)nodeList1.item(0)).getElementsByTagName("ROLE");
        NodeList arcList = ((Element)nodeList2.item(0)).getElementsByTagName("ROLE");
        Assert.assertEquals(1, engList.getLength());
        Assert.assertEquals(1, arcList.getLength());

        String eng = engList.item(0).getTextContent().trim();
        String arc = arcList.item(0).getTextContent().trim();
        Assert.assertEquals("Architect", arc);
        Assert.assertEquals("Engineer", eng);
    }
}

请检查您的代码,因为某处有问题(文件编码?)

我的问题已解决。非常感谢大家的帮助并为我提供见解。这不是下划线的问题,而是我的代码中隐藏的响应过滤器的问题,我不知道并通过调试找出答案。