2011-05-06 32 views
3


我有一个datacontract对象,我可以使用DataContractSerializer成功将它序列化为一个xml,但是当我试图访问一次使用XPath的节点时,它返回null。我无法找出它为什么会发生。XPath不能在xml中使用DataContractSerializer创建

这是我到目前为止。

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

@marc_s它使用一个更多的命名空间: - “http://www.w3.org/2001/XMLSchema-instance”,但即使在添加这行后namesapceManager.AddNamespace(“i”,“http:// www .w3.org/2001/XMLSchema的实例“); ,我得到它只为null – wizzardz 2011-05-06 05:01:33

+0

无论出于何种原因,用'“”'前缀添加该名称空间似乎不起作用。如果我添加一个'ns ='前缀并使用该前缀,它对我来说工作得很好...... – 2011-05-06 05:06:34

回答

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); 
} 

现在它工作得很好 - 名字打印到 安慰。

+1

谢谢你的工作:) – wizzardz 2011-05-06 05:10:44