我正在将一个包含以下结构的字符串加载到XML文档中:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Include="clsWorker.cs" />
</ItemGroup>
</Project>
然后我将所有内容加载到一个 XmlDocument
中:
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(Xml);
然后出现了以下问题:
XmlNode Node = xmldoc.SelectSingleNode("//Compile"); // returns null
如果我从根元素(Project
)中删除xmlns
属性,它就能正常工作。
我该如何让SelectSingleNode
返回相关的元素?
SelectNodes
吗? - T.S.SelectSingleNode("xpath")
大致相当于SelectNodes("xpath")[0]
。 - Frédéric HamidiXmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable); foreach (XmlAttribute curAttribute in xml.DocumentElement.Attributes) { if (curAttribute.Prefix.Equals("xmlns")) { ns.AddNamespace(curAttribute.LocalName, curAttribute.Value); } }
- Ravendarksky