首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当我的XML标记中包含"_“时,无法从文档中检索节点列表

问当我的XML标记中包含"_“时,无法从文档中检索节点列表
EN

Stack Overflow用户
提问于 2017-01-17 14:39:58
回答 2查看 538关注 0票数 0

我有一个这样的xml

代码语言:javascript
复制
<PARENT>
<TAG_1>
<ROLE>Architect </ROLE>
</TAG_1>
<TAG2>
<ROLE>Architect </ROLE>
</TAG2>
</PARENT>

我使用JAX-B框架进行编组和UnMarshalling。

问题是,当我检索org.w3c.dom.NodeList时,我可以对不包含_的TAG2执行操作,而不能对包含_(下划线)的TAG1执行操作。

org.w3c.dom.NodeList nodeList = org.w3c.dom.Document.getElementsByTagName("TAG2")
返回长度为1,这是正确的。

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

谁能建议下划线有什么问题,以及如何处理它,因为XML我不能根据客户的要求进行更改。

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-17 16:20:34

好吧,这对我很有效:

代码语言:javascript
复制
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);
    }
}

请检查您的代码,因为有错误的地方(文件编码?)

票数 0
EN

Stack Overflow用户

发布于 2017-01-17 18:07:23

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41690539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档