天天看點

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/";