2009-04-27 88 views
1

我試圖進一步瞭解LINQ到XML,所以我讓自己變得整潔示例XML文檔來嘗試一下。另外,我嘗試(併成功)爲該文件創建了自己的XML模式,只是爲了測試一下。該XML文檔是非常簡單的,和幾乎是這樣的:當我的XML文檔中的xmlns屬性添加到根元素時,我的linq查詢不起作用

<cars xmlns="/carsSchema.xsd"> 
    <car age="5"> 
    <carId>1</carId> 
    <brand>BMW</brand> 
    <model>320i</model> 
    <color paintType="metallic">Red</color> 
    </car> 

    <car age="2"> 
    <carId>2</carId> 
    <brand>VW</brand> 
    <model>Golf</model> 
    <color paintType="matt">White</color> 
    </car> 
[...] 
</cars> 

現在,查詢這個文件,如果我從根元素刪除xmlns -attribute工作得很好。當我將它添加回來時,查詢返回null並且不返回任何內容。我試圖找出自己,但我還沒有找到一種解決方案來解決我的問題。

這裏是C#位:

 XDocument xmlDoc = XDocument.Load(currentDir + "\\Cars.xml"); 

// XNamespace ns = "{" + currentDir + "\\carSchema.xsd}"; 
// Tried to query xmlDoc.Descendants(ns+"car") after reading another post, 
// but that made no difference 

     var carInfo1 = from car in xmlDoc.Descendants("car") 
         select (string)car.Element("brand") + ": " + (string)car.Element("model"); 

有人看到有什麼不對?爲什麼LINQ真的很在乎關於命名空間呢?它不能只是查詢我的文件,不關心它?

在此先感謝! :-)

回答

3

當您通過後代和元素進行搜索時,需要指定名稱空間。 LINQ to XML非常簡單。它看起來像你幾乎沒有,但對於要素沒有做到這一點:

XDocument xmlDoc = XDocument.Load(currentDir + "\\Cars.xml"); 
// I don't think namespace URIs are really resolved. I'm not sure though - 
// for a proof of concept, I suggest you use a namespace of 
// http://dummy.com/dummy.xsd 
XNamespace ns = "/carSchema.xsd"; 

var carInfo1 = from car in xmlDoc.Descendants(ns + "car") 
        select (string)car.Element(ns + "brand") + ": " + 
          (string)car.Element(ns + "model"); 
+0

現在,它修復了它。非常感謝!但是,有沒有辦法讓LINQ忽略名稱空間,除了首先將它從XML-doc中移除? – 2009-04-27 14:03:24

1

當你使用一個虛構這也適用的「http://」 URI的命名空間。你是對的。它沒有解決。

 private XNamespace ns = "http://schemas.xin2009.com/DataMap/2009"; 

       IEnumerable<string> names = (from spnode in _map.Descendants(ns + "Entity") 
             where spnode.Attribute("name").Value == this.Entity 
             select spnode.Element(ns + "StoredProcedure").Attribute("name").Value); 

注意命名空間的ns只需要添加到元素而不是屬性。

相關問題