【问题标题】:java read xml root node description using JAXPjava使用JAXP读取xml根节点描述
【发布时间】:2013-05-24 12:20:28
【问题描述】:

我有一个简单的 xml 文档,我正在尝试使用 org.w3c.dom.Document 获取根节点的描述

<?xml version="1.0" encoding="ISO-8859-1"?><students   mlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="students.xsd"><description>A bunch students and courses</description><student studentID="0144085" gender ="M"><firstname>Jack</firstname>

这是我的代码

DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                    .newInstance();
            builderFactory.setNamespaceAware(true);
            builderFactory.setValidating(true);
            builderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE,
                    W3C_XML_SCHEMA);
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            // parse the input stream
            document = builder.parse(in);
            document.getDocumentElement().normalize();
            // JAXP
            Node rootXMLNode = document.getDocumentElement();

            DOMParser parser = new DOMParser();
            //jf : set StudentINfoSet class properties
            this.description = rootXMLNode.getTextContent();
                    //DOMUtilities.getAttributeString(rootXMLNode,"description");

现在是 rootXMLNode.getTextContent();将整个xml文档作为字符串返回,那我怎么才能得到根节点的描述标签呢。

非常感谢。

【问题讨论】:

    标签: java xml dom


    【解决方案1】:

    有很多方法,但最简单的方法是使用getElementsByTagName 之类的方法来获取description 元素,然后使用getTextContent

        Element rootXMLNode = document.getDocumentElement();
    
        //jf : set StudentINfoSet class properties
        this.description = rootXMLNode.getElementsByTagName( "description" )
                .item( 0 ).getTextContent();
    

    但是,使用 XPath 之类的东西可能会更好...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多