2011-05-06 31 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