我嘗試從Visual Studio * .csproj文件中查詢元素。我創建了一個簡短的例子來說明問題:使用xmlns屬性查詢XDocument屬性(名稱空間)
// Working
string xml1 = @"<Project ToolsVersion='4.0'>
<ItemGroup Label='Usings'>
<Reference Include='System' />
<Reference Include='System.Xml' />
</ItemGroup>
</Project>";
// Not working
string xml2 = @"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup Label='Usings'>
<Reference Include='System' />
<Reference Include='System.Xml' />
</ItemGroup>
</Project>";
XDocument doc = XDocument.Parse(xml2);
foreach (XElement element in doc.Descendants("ItemGroup"))
{
Console.WriteLine(element);
}
字符串xml1工作正常,xml2不返回任何內容。這些字符串之間的唯一區別是文檔根目錄中的xmlns屬性。
如何查詢包含xmlns屬性的文檔? 爲什麼xml文檔包含xmlns屬性時會出現問題?
另一種語法:'doc.Descendants(「{http://schemas.microsoft.com/developer/msbuild/2003}ItemGroup」)' – ziya
對不起,我不明白爲什麼我們必須明確寫入命名空間,如果它這個文件的默認值是? XElement/XDocument本身沒有解決這個問題的原因是什麼? –
@FelixKeil:因爲當你調用'Element'或者'Descendants'時,你指定了一個'XName',它是完全限定的......並且完全限定的名字包含了命名空間。我有點看到你的觀點,但我認爲它的完成方式是有道理的,而LINQ to XML中的名稱空間支持是我見過的任何XML API中最好的。 –