c# – XPath无法在使用DataContractSerializer创建的xml中工作

我有一个datacontract对象,我能够使用DataContractSerializer将其成功序列化为xml,但是当我尝试使用XPath访问该节点时,它返回null.我无法找到它为什么会这样.

这是我到目前为止所要做的.

namespace DataContractLibrary
{
    [DataContract]
    public class Person
    {
        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        [DataMember]
        public int Age { get; set; }
    }
}

static void Main(string[] args)
{
    Person dataContractObject = new Person();
    dataContractObject.Age = 34;
    dataContractObject.FirstName = "SomeFirstName";
    dataContractObject.LastName = "SomeLastName";

    var dataSerializer = new DataContractSerializer(dataContractObject.GetType());

    XmlWriterSettings xmlSettings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8, OmitXmlDeclaration = true };
    using (var xmlWriter = XmlWriter.Create("person.xml", xmlSettings))
    {
        dataSerializer.WriteObject(xmlWriter, dataContractObject);
    }

    XmlDocument document = new XmlDocument();
    document.Load("person.xml");

    XmlNamespaceManager namesapceManager = new XmlNamespaceManager(document.NameTable);
    namesapceManager.AddNamespace("", document.DocumentElement.NamespaceURI);

    XmlNode firstName = document.SelectSingleNode("//FirstName", namesapceManager);

    if (firstName==null)
    {
        Console.WriteLine("Count not find the node.");
    }

    Console.ReadLine();
}

谁能让我知道我的错误?
非常感谢您的帮助.

最佳答案
您忽略了放入序列化XML的XML命名空间:

<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://schemas.datacontract.org/2004/07/DataContractLibrary">
   <Age>34</Age>
   <FirstName>SomeFirstName</FirstName>
   <LastName>SomeLastName</LastName>
</Person>

因此,在您的代码中,您需要引用该命名空间:

XmlNamespaceManager namespaceManager = new XmlNamespaceManager(document.NameTable);
namespaceManager.AddNamespace("ns", document.DocumentElement.NamespaceURI);

然后在XPath中,您需要使用该命名空间:

XmlNode firstName = document.SelectSingleNode("//ns:FirstName", namespaceManager);

if (firstName == null)
{
   Console.WriteLine("Could not find the node.");
}
else
{
   Console.WriteLine("First Name is: {0}", firstName.InnerText);
}

现在它工作得很好 – 名称被打印到控制台上.

转载注明原文:c# – XPath无法在使用DataContractSerializer创建的xml中工作 - 代码日志