Android - 如何使用标记中的冒号解析XML? [英] Android - How to parse an XML with colon in tags?

查看:184
本文介绍了Android - 如何使用标记中的冒号解析XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的XML文件:



I have an XML file like this :

<item>  
  <title>...</title>  
  <link>...</link>    
  <pubDate>...</pubDate>
  <description>...</description>
  <media:content url=" ....." type="image/jpg" medium="image" height="270" width="480" />
</item>





我想在 media:content 标签中获取属性 url

但我不知道怎么做?

我只得到< title>,< link>,< pubDate>,< description>使用DOM Parser。



请帮帮我!谢谢和最好的关注!!!



I want to get attribute url in media:content tag.
But I don't know how to do this?
I only get <title>, <link>, <pubDate>, <description> using DOM Parser.

Please help me! Thanks and best regard!!!

推荐答案

media:content 节点名称意味着此节点属于当前使用别名 media 的XML命名空间。



在文档的某处,您应该看到命名空间声明:

The media:content node name means that this node is part of the XML namespace which is currently using the alias "media".

Somewhere in your document, you should see the namespace declaration:
<someNode xmlns:media="..."



(如果不这样做,那么XML格式不正确。)



根据这个SO线程 [ ^ ],你应该调用 setNamespaceAwar e(true) DocumentBuilderFactory 对象上,并使用 getElementsByTagNameNS 方法阅读elements。


(If you don't, then the XML is malformed.)

According to this SO thread[^], you should call setNamespaceAware(true) on your DocumentBuilderFactory object, and use the getElementsByTagNameNS method to read the elements.


这不是Android问题,而是XML问题。您尝试引用的XML元素包含名称空间,即 media 。您需要先导入XML命名空间,然后才能引用它。



我不完全确定你是如何在Java中实现这一点的(我假设你是用Java做的)但在C#中,代码类似于以下。



This is not an Android issue but an XML issue. The XML element you are trying to reference contains a namespace i.e. media. You need to import the XML namespace before you can reference it.

I'm not entirely sure how you achieve this in Java (I'm assuming you are doing this in Java) but in C# the code would be similar to the following.

XNamespace nsMedia = "media"; //the actual namespace may be at the top of the XML document
foreach (XElement xItem in xItems.Elements("item"))
{
  XElement xContent = xItem.Element(nsMedia + "content"); 
  XAttribute xUrl = xContent.Attribute("url");
  string url = xUrl.Value;
}


这篇关于Android - 如何使用标记中的冒号解析XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆