xml如何在前面选择带命名空间的节点?

时间:2013-09-02 05:20:31

标签: xml c#-4.0

我有这个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');

1 个答案:

答案 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);