我有一个简单的 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文档作为字符串,那么我怎样才能获取根节点的描述标签。
非常感谢。
最佳答案
方法有很多,但最简单的方法是使用 getElementsByTagName
等方法来获取 description
元素,然后使用 getTextContent
。
Element rootXMLNode = document.getDocumentElement();
//jf : set StudentINfoSet class properties
this.description = rootXMLNode.getElementsByTagName( "description" )
.item( 0 ).getTextContent();
但是,使用 XPath 之类的东西可能会更好...
关于java 使用JAXP读取xml根节点描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16734858/