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');
4

1 回答 1

1

您正在混合使用 LINQ to XML(类)和XElement老式方法。XmlDocumentSelectSingleNode

您应该改用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);
于 2013-09-02T05:32:42.200 回答