C# XPATHSelectElements返回null(XML文件中没有名称空间)
我使用的XML文件不包含名称空间:C# XPATHSelectElements返回null(XML文件中没有名称空间),c#,xml,xpath,linq-to-xml,C#,Xml,Xpath,Linq To Xml,我使用的XML文件不包含名称空间: string xmlFile = GetCountriesFile(); XDocument xd = XDocument.Load(xmlFile); XElement city = xd.XPathSelectElement("/WorldCities/City"); Console.Clear(); // Print the name of the first city Console.WriteLine(city.Element("Name").
string xmlFile = GetCountriesFile();
XDocument xd = XDocument.Load(xmlFile);
XElement city = xd.XPathSelectElement("/WorldCities/City");
Console.Clear();
// Print the name of the first city
Console.WriteLine(city.Element("Name").Value);
// Get all the cities in the document
// Works in http://xpath.online-toolz.com/tools/xpath-editor.php
// but returns null in .NET
var cities = xd.XPathSelectElements("/WorldCities/City");
// cities is set to nulll
Console.ReadKey();
温哥华
加拿大
北美
布宜诺斯艾利斯
阿根廷
南美洲
柏林
德国
欧洲
内罗毕
肯尼亚
非洲
东京
日本
亚洲
悉尼
澳大利亚
澳大利亚
当我对同一XML使用XPATH路径“/WorldCities/City”时,位于的XPATH测试人员返回了所有城市元素。那么为什么XPATHSelectElements方法返回null?XML文件中没有引起问题的名称空间。您的XPath是正确的,并且您的代码与您提供的XML配合良好-第一次查询返回第一个城市元素,第二次查询返回6个城市的集合:
我的第一个想法是您正在加载其他文件。但是第一个查询返回第一个城市元素,第二个查询应该至少返回一个城市。看起来第二个查询没有使用相同的xpath。确保您的实际代码与您提供的代码完全相同。该方法从不返回null,而是返回一个
IEnumerable
,您必须在代码中使用它才能访问集合中的元素(如果选择了任何元素)。但是该方法不会得到空值。我检查了xd变量,它包含正确的XML文本,这意味着它从正确的XML文件中获取文本。我可以使用DataSet和LINQ查询城市,只有XPATHSelectElements方法返回null。@user3147936使用您提供的代码和数据,它不返回null当我在即时窗口中键入“cities”时,它在下面返回null结果,这就是为什么我说该方法返回null:“cities”{System.Xml.XPath.xpatheevaluator.evaluateInterator}result:null“无论如何,我在城市之后添加了下面的代码,并且我能够打印城市的名称。感谢你们的帮助。foreach(城市中的XElement c){Console.WriteLine(c.Element(“Name”).Value);}
<?xml version="1.0" encoding="utf-8" ?> <!-- XML declaration, there can only be one XML declaration in an XML document -->
<WorldCities> <!-- Root node, there can only be one root node in an XML document -->
<City> <!-- Parent node -->
<Name>Vancouver</Name> <!-- Child node -->
<Country>Canada</Country> <!-- Sibling node of location -->
<Continent>North America</Continent> <!-- Sibling node of location -->
</City>
<City>
<Name>Buenos Aires</Name>
<Country>Argentina</Country>
<Continent>South America</Continent>
</City>
<City>
<Name>Berlin</Name>
<Country>Germany</Country>
<Continent>Europe</Continent>
</City>
<City>
<Name>Nairobi</Name>
<Country>Kenya</Country>
<Continent>Africa</Continent>
</City>
<City>
<Name>Tokyo</Name>
<Country>Japan</Country>
<Continent>Asia</Continent>
</City>
<City>
<Name>Sydney</Name>
<Country>Australia</Country>
<Continent>Australia</Continent>
</City>
</WorldCities>