【问题标题】:get value of element in xml-file using JDOM使用 JDOM 获取 xml 文件中元素的值
【发布时间】:2012-08-25 07:41:26
【问题描述】:

我有xml文件

<?xml version="1.0" encoding="UTF-8"?>
<products xmlns="http://www.myapp.com/shop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.myapp.com/shop shop.xsd">
    <category name="yyy">
        <subcategory name="yyy1">
            <goods name="yyy11">                
                <model>ferrari</model>              
            </goods>
        </subcategory>
    </category>
</products>

我尝试获取元素 &lt;model&gt; 的值

SAXBuilder builder = new SAXBuilder();
File xmlProductFile = new File("shop.xml");
Document document = builder.build(xmlProductFile);
Element rootNode = document.getRootElement();       

String category = rootNode.getChild("model").getText();

但我得到的是空值

【问题讨论】:

  • 嗨,Ray,可能让您感到困惑的一个问题是元素上的命名空间。如果您希望能够选择元素,则需要为所有 JDOM 方法提供一个命名空间实例。例如,rootNode.getChild("category") 将不返回任何内容,但 rootNode.getChild("category", Namespace.getNamespace("myapp.com/shop")) 将返回类别元素

标签: java xml xml-parsing jdom jdom-2


【解决方案1】:

必须必须使用getDescendants(Filter&lt;F&gt;) 方法来选择特定的Element

Element root = document.getRootElement();
ElementFilter filter = new org.jdom2.filter.ElementFilter("model");
for(Element c : root.getDescendants(filter)) {
    System.out.println(c.getTextNormalize());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2019-04-11
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多