String转w3cDocument及解析都是null

fgod 发布于 2017/09/11 23:01
阅读 1K+
收藏 0

【开源中国 APP 全新上线】“动弹” 回归、集成大模型对话、畅读技术报告”

 各位好,我在使用String转Docment时,总是获取到[#document: null]

 @Test
    public void test01ParseDocment() throws Exception {
         
       StringBuilder sb = new StringBuilder();
       sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><root>")
       .append("<item><name>").append("a").append("</name>")
       .append("<no>").append(100).append("</no></item>")
       .append("</root>");
       
       Document w3cDoc = strToW3cDoc(sb.toString());
       logger.info("doc={}", w3cDoc.toString());
       parseDoc(w3cDoc);
    }

    private Document strToW3cDoc(String xmlString){
    
        Document doc = null;
        try(InputStream is = new ByteArrayInputStream(xmlString.getBytes())){
            
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
            DocumentBuilder builder=factory.newDocumentBuilder(); 
            doc = builder.parse(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

    private void parseDoc(Document doc) {
        Element element = doc.getDocumentElement();
        logger.info("element={}", element.toString());
        NodeList children = element.getChildNodes();
        logger.info("children={}", element.toString());
        Node node = children.item(0);
        logger.info("node={}", element.toString());
    }

本想初始化出一个org.w3c.dom.Document对象(不考虑dom4j或其他),来跑单元测试测一个现有的接口结果处理工具类。。没想到实例化Docment过不了。。

  打印结果:

c.p.e.u.ClassName-doc=[#document: null]
c.p.e.u.ClassName-element=[root: null]
c.p.e.u.ClassName-children=[root: null]
c.p.e.u.ClassName-node=[root: null]

尝试了把内容写进文件,InputStream直接读file内容,结果一样。

求解为何出现这种内容,是转换过程不对还是解析不对呢?

 

加载中
0
如比如比
如比如比

首先这部分的代码有坑:

        logger.info("children={}", element.toString());
        Node node = children.item(0);
        logger.info("node={}", element.toString());

至于输出内容:看下各种元素的父类NodeImpl的toString():

    public String toString() {
        return "["+getNodeName()+": "+getNodeValue()+"]";
    }

是节点名+节点值的的格式,后面有null很正常。然并不代表着这个节点没有取到值而不能使用。

比如:node.getChildNodes().item(0).getTextContent()的话,是完全可以获得到a的。

 

 

f
fgod
是的,今天仔细看了各个对象的各方法,发现父子关系以及节点设定确实不同,<name>aa</name> 会解析成两个节点,父节点name,值为null,而子节点 text:aa
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部