1

我有一个 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;
4

1 回答 1

4

使用XmlSerializer类并为XmlElementXmlRoot属性指定命名空间:

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>
于 2012-09-27T14:17:22.560 回答