使用Jdom和SAX Parser解析XML文件

时间:2012-04-30 06:04:59

标签: java xml sax jdom

我的XML格式为:

<response>

<result name="response" numFound="295" start="0">
<doc>
<str name="Content">...</str>
<str name="Latitude">36.48617</str>
<str name="Longitude">-89.97065</str>
<str name="id">00000001 pages 1-249.pdf</str>
</doc>
<doc>
<str name="Content">...</str>
<str name="Latitude">33.59927</str>
<str name="Longitude">-86.69304</str>
<str name="id">100-449923 section 26 -114.pdf</str>
</doc>
<doc>

我需要在变量中找到内容,纬度和经度的值。到目前为止,我的代码是:

SAXBuilder sax=new SAXBuilder();
Document doc= (Document) sax.build(new StringReader(xmlstr));
Element rootElem=doc.getRootElement();
out.println("rootElem = " + rootElem.toString());
Element res=rootElem.getChild("result");
List docs=res.getChildren("doc");

for(int i=0;i<docs.size();i++)
{
    out.println("docsSize = " + docs.size());
    Element row= (Element)docs.get(i);
    //List strs= docs(i).getChildren("str");
    List strs=row.getChildren("str");
    for(int j=0;j<strs.size();j++){
        out.println("strs = " + strs.size());
        //out.println(strs.get(j).getValue());
        List column =  (List)strs.get(j);
        if(column.getAttribute("name").getValue()=='Content')
            {
            out.println("Hi");
            out.println(column.getAttribute("name").getValue());
            out.println("Bi");
            }
        //String Content = column.getAttribute("name").get(1).getValue();
        //String value = column.getText();
        //out.println("Content = " + Content);
        //out.println("value = " + value);
    }
    //out.println(content);
    break;
}
}catch(Exception e)
{
    out.println(e);
}   

但是我仍然无法获得纬度和经度值,即使我得到它们所在阵列的大小。你能不能提出同样的建议

4 个答案:

答案 0 :(得分:1)

这个if(column.getAttribute(“name”)。getValue()=='Content')只允许内容。 所以纬度和经度不会进入您打印值的if条件。

尝试 if(column.getAttribute(“name”)。getValue()!='id'),它会打印内容,纬度和经度。

答案 1 :(得分:1)

在Java中编写这样的低级导航代码非常冗长且容易出错。为什么不将XPath与Java代码结合使用,或者更好的是,在XQuery或XSLT中编写整个内容?

答案 2 :(得分:0)

如果要按名称检索属性:

for(int j=0;j<strs.size();j++){
    out.println("strs = " + strs.size());
    Element column =  (Element) strs.get(j);
    out.println("Content: " + column.getAttributeValue("Content"));
    out.println("Latitude: " + column.getAttributeValue("Latitude"));
    out.println("Longitude: " + column.getAttributeValue("Longitude"));
    out.println("id: " + column.getAttributeValue("id"));
}

如果要迭代属性:

for(int j=0;j<strs.size();j++){
    out.println("strs = " + strs.size());
    Element column =  (Element) strs.get(j);
    for (Attribute a : column.getAttributes())
      out.println("Name: " + a.getName() + " Value: " + a.getValue());
}

答案 3 :(得分:0)

你有一些问题。

我认为如果您修复字符串比较,您的代码将达到预期效果......

if(column.getAttribute("name").getValue()=='Content')

永远不会奏效。在String值上使用==运算符很少是“正确的”。

尝试:

if("Content".equals(column.getAttribute("name").getValue()))

哦,我看到你的整个单引号意味着你没有给我们你真正的Java代码....围绕'内容'的单引号甚至不会编译....

相关问题