java Document里判断XML文件中有无此节点

<tiripPackage>

- <businessContent>

- <subPackage>

<id>001</id>

<content>123</content>

</subPackage>

</businessContent>

</tiripPackage>

怎么判断xml文件里有没有节点content
Document xmlDoc = DocumentHelper.parseText(str);
Element root = xmlDoc.getRootElement();//根节点
String content = root.element("content"); //如果没有content就报异常了

Document 这个类里没有直接判断有无次节点方法吗?

使用 XPath。

        try (final FileReader reader = new FileReader("xpathexample.xml")){
            XPath xpath = XPathFactory.newInstance().newXPath();
            String expression = "count(//content)";
            InputSource source = new InputSource(reader);
            Number count = (Number) xpath.evaluate(expression, source, XPathConstants.NUMBER);
            System.out.println(count.intValue());
        } catch (final IOException | XPathExpressionException e) {
            System.err.println(e.getMessage());
        }

 

dom4j 可以使用 Document的selectSingleNode 返回null的就是没有

<PrimaryKey><Key Ref="o30"/></PrimaryKey>

val node = doc.selectSingleNode("//PrimaryKey/Key/@R")
node: org.dom4j.Node = null

val node = doc.selectSingleNode("//PrimaryKey/Key/@Ref")
node: org.dom4j.Node = org.dom4j.tree.DefaultAttribute@151d52e [Attribute: name Ref value "o30"]

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-09
private void doublexml(Element ele)
{
StringBuilder sb = new StringBuilder();

for(Iterator i = ele.elementIterator();i.hasNext();)
{
Element node = (Element)i.next();
System.out.println("节点名:"+node.getName());
String nodeName = node.getName();
if(node.attributes()!=null && node.attributes().size()>0)
{
for(Iterator j = node.attributeIterator();j.hasNext();)
{
Attribute item = (Attribute)j.next();
System.out.print("属性名:"+item.getName()+"\t属性值:"+item.getValue()+"\n");
}
}
if(node.getText().length()>0)
{
System.out.println("节点值:"+node.getText());
String nodeText = node.getText();
}
if(node.elementIterator().hasNext())
{
this.doublexml(node);
}
}
}
第2个回答  推荐于2017-11-26
获取节点名称然后和content做比较就可以了本回答被网友采纳
第3个回答  2013-09-09
Document doc = DocumentHelper.parseText(ss);
Element root = doc.getRootElement();
Element content = root.element("content ");

你判断下content.getText(); 是不是空


LZ,你直接用String接受 root.element("content"); 不会包错吗?

try——catchy一下 捕捉那个异常就是了

追问

不是content里面的内容为空,而是没有content这个节点

第4个回答  2013-09-09
你会读xml文件中节点吧,然后读出来看看是否为空就可以了 具体怎么写我记不得了追问

我读节点,如果没有此节点直接报异常了

追答

遍历所有节点,判断这些节点中是否包含你要的节点

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网