Skip to main content
 首页 » 编程设计

c#之问一下c#反序列化

2024年02月20日15mate10pro

我有一个 XML:

<g1:Person xmlns:g1="http://api.google.com/staticInfo/"> 
  <g1:Id> 005008</g1:Id> 
    <g1:age>23></g1:age> 
    </g1:Person> 

如何将其反序列化为 Person 对象。

我只是想办法。

  XmlDocument xdc = new XmlDocument(); 
                xdc.Load(xmlpath); 
 
                xdc.LoadXml(xdc.InnerXml.Replace("g1:","")); 
 
                xdc.Save(xmlpath); 

任何其他让它变得简单的方法。或使用它的高级方法。

        xs = new XmlSerializer(typeof(Person)); 
        XmlDocument xdc = new XmlDocument(); 
        xdc.Load(xmlpath); 
 
        xdc.LoadXml(xdc.InnerXml.Replace("g1:","")); 
 
        xdc.Save(xmlpath); 
 
 
      Stream  stm = new FileStream(xmlpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
 
   Person p= xs.Deserialize(stm) as Person; 

请您参考如下方法:

使用 XmlSerializer类并为 XmlElement 指定命名空间和 XmlRoot属性:

using System.Xml.Serialization; 
 
... 
 
// TODO: Move the namespace name to a const variable 
[XmlRoot(ElementName = "Person", Namespace = "http://api.google.com/staticInfo/")] 
public class Person 
{ 
    [XmlElement(ElementName="Id", Namespace="http://api.google.com/staticInfo/")] 
    public int ID { get; set; } 
    [XmlElement(ElementName = "age", Namespace = "http://api.google.com/staticInfo/")] 
    public int Age { get; set; } 
} 
 
... 
 
string input = 
    @"<g1:Person xmlns:g1=""http://api.google.com/staticInfo/""> 
        <g1:Id>005008</g1:Id> 
        <g1:age>23</g1:age> 
      </g1:Person>"; 
 
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person)); 
Person person = (Person)xmlSerializer.Deserialize(new StringReader(input)); 

或者,可以在 XmlSerializer 的构造函数中指定默认命名空间,并且不指定 Namespace 属性:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person),  
    "http://api.google.com/staticInfo/"); 

为确保命名空间前缀为“q1”,请指定 XmlSerializerNamespaces使用。例如:

Person person; // Assuming it is populated as above 
using(MemoryStream memoryStream = new MemoryStream()) 
{ 
    xmlSerializer.Serialize(memoryStream, person,  
        new XmlSerializerNamespaces(new [] { new XmlQualifiedName("q1", "http://api.google.com/staticInfo/") })); 
    memoryStream.Flush(); 
    Console.Out.WriteLine(Encoding.UTF8.GetChars(memoryStream.GetBuffer())); 
} 

显示:

<?xml version="1.0"?> 
<q1:Person xmlns:q1="http://api.google.com/staticInfo/"> 
  <q1:Id>5008</q1:Id> 
  <q1:age>23</q1:age> 
</q1:Person>