天天看点

XML解析中的namespace初探

初学者在解析XML文件的时候最容易遇到的问题恐怕就是XML的namespace了,本文旨在对namespace做一个简要的介绍。

namespace的意义无需多说,和C++,C#等高级语言一样,XML同样面临大量文件放在一起的时候变量重名的问题,所以要用namespace把名字相同意义不同的变量隔离开。本文着重讨论namespace的解析方法。

以下是一个简单的XML文件:

<root>    <child id = ‘0’>       hello world    </child>    <child id='1'>      one </root>

这个例子里面没有namespace,大家初学XML时接触的例子恐怕都是这样的。这种例子具有误导性,初学者解析出了hello world之后就兴高采烈的拿同样的程序去解析实际的XML文件,往往铩羽而归。下面是一段豆瓣API返回的XML文件

<?xml version="1.0" encoding="UTF-8"?>   <title>Debugging the Web </title>   <author>     name>胖胖的大头鱼</name> </author> <db:attribute name="invite_only">no</db:attribute>

    看到这么多www就不想看直接跳过,然后看到熟悉的<author> </author>, 果断套用上面例子的程序,一运行却啥都得不到,问题到底出在哪?C#提供一大堆的XML类,XDocument, XReader, XPath, XmlDocument,是不是我现在用的这种类不给力啊,没法确定只好乱试,一乱试一晚上就过去了。童鞋,我们还是静下心来逐行看看吧。

那么该如何解析呢?这里提供一个样例程序,希望对大家有帮助。这个代码可以在WP7上运行。我还有一个版本用的XmlDocument,尼玛WP7上木有这个类,坑爹的。。。

            string file = @"C:\Users\v-menlin\Documents\Visual Studio 2010\Projects\test\test\test.xml";             XDocument doc = XDocument.Load( file );             //use following code to parse a string             //XDocument doc = XDocument.Parse( string );             //对于XML文件中所有的没加类似db:这种的元素,用下列方法             foreach ( XElement element in doc.Descendants( d + "title" ) )             {                 Console.WriteLine( element.Value );             }             //<author>下面包含了<link>,一下的例子还示例了如何读取属性。             foreach ( XElement element in doc.Descendants( d + "author" ) )                 foreach ( XElement inelement in element.Descendants( d + "link" ) )                 {                     Console.WriteLine( inelement.Attribute( "href" ).Value );                     Console.WriteLine( inelement.Attribute( "rel" ).Value );                 }             Console.WriteLine();             //对于加了冒号前缀的元素,使用下列代码             foreach ( XElement element in doc.Descendants( db + "attribute" ) )                 Console.WriteLine( element.Attribute( "name" ).Value );             //其实只是NameSpace的头部换了一下。             //下面列出其他几个常用头部,直接换用。             XNamespace opensearch = @"http://a9.com/-/spec/opensearchrss/1.0/";