我有一个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();
}
任何人都可以让我知道我的错误吗? 非常感谢您的帮助。
答案 0 :(得分:5)
您忽略了放入序列化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);
}
现在它工作正常 - 名字被打印到控制台上。