我有这个xml:
XNamespace g = "http://something.com";
XElement contacts =
new XElement("Contacts", new XAttribute(XNamespace.Xmlns + "g", g),
new XElement("Contact",
new XElement(g + "Name", "Patrick Hines"),
new XElement("Phone", "206-555-0144"),
new XElement("Address",
new XElement("street", "this street"))
)
);
我想选择gName元素,所以我尝试过但不起作用:
var node = doc.SelectSingleNode("/Contacts/g:Name[text()=Patrick Hines');
答案 0 :(得分:1)
您正在使用XElement
方法混合使用LINQ to XML(XmlDocument
类)和老式SelectSingleNode
。
你应该使用XNode.XPathSelectElement
方法,但是使用命名空间它比使用方法调用更棘手。
首先,您必须使用IXmlNamespaceResolver
属性创建XmlReader.NameTable
实例:
var reader = doc.CreateReader();
var namespaceManager = new XmlNamespaceManager(reader.NameTable);
namespaceManager.AddNamespace("g", g.NamespaceName);
然后你可以查询你的文件:
var doc = new XDocument(contacts);
var node = doc.XPathSelectElement("/Contacts/Contact/g:Name[text()='Patrick Hines']", namespaceManager);