【问题标题】:How to parse xml with namespace using android sax parser如何使用 android sax 解析器解析带有命名空间的 xml
【发布时间】:2011-10-19 01:11:24
【问题描述】:

我的 XML 文档如下所示:

<?xml version="1.0" encoding="iso-8859-1" standalone="yes"?>
<feed xml:base="http://localhost/someApp" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
    <entry>
       <id>An ID here</id>
       <content type="application/xml">
           <m:properties>
              <d:Name>The name I want to get</d:Name>
           </m:properties>
       </content>
     </entry>
</feed>

我可以使用以下代码从 id 标记中获取“此处的 ID”:

String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
RootElement root = new RootElement(ATOM_NAMESPACE, "feed");
Element entry = root.getChild(ATOM_NAMESPACE, "entry");
Element id = entry.getChild(ATOM_NAMESPACE, "id");

id.setEndTextElementListener(new EndTextElementListener(){
    public void end(String body){
        messages.add(body); // messages = ArrayList<String>
    }
});

但是,我似乎无法获得“我想要的名字”。

我添加了这段代码:

String METADATA_NAMESPACE = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
String DATASERVICES_NAMESPACE = "http://schemas.microsoft.com/ado/2007/08/dataservices";
Element content = entry.getChild(ATOM_NAMESPACE, "content");
Element properties = content.getChild(METADATA_NAMESPACE, "properties");
Element name = properties.getChild(DATASERVICES_NAMESPACE, "name");
name.setEndTextElementListener(new EndTextElementListener(){
    public void end(String body){
        messages.add(body);
    }
});

但没有任何内容被添加到消息列表中。

我需要做什么才能获得d:Name

【问题讨论】:

  • 在您使用的代码中"name",而XML 有一个本地名称为Name 的标签。会不会是那个大写字母? XML 区分大小写。

标签: java android sax saxparser


【解决方案1】:

正如 G_H 指出的那样,问题在于我没有大写 "name"

这行得通:

Element name = properties.getChild(DATASERVICES_NAMESPACE, "Name"); // 'Name' instead of 'name'
name.setEndTextElementListener(new EndTextElementListener(){
    public void end(String body){
        messages.add(body);
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 2011-04-30
    • 2011-06-17
    • 2021-10-24
    • 2019-03-17
    • 2023-04-03
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多