2010-11-09 217 views
3

如何使用C#将以下CatalogProduct标签解除为我的CatalogProduct对象?将XML反序列化为C#对象

<?xml version="1.0" encoding="UTF-8"?> 
<CatalogProducts> 
    <CatalogProduct Name="MyName1" Version="1.1.0"/> 
    <CatalogProduct Name="MyName2" Version="1.1.0"/> 
</CatalogProducts> 

注意我没有CatalogProducts对象,因此要跳过该元素拉回时,进入反序列化

感谢

+0

这不是一个反序列化,因为它不是序列化的结果。我可以说这只是一个解析或创建一个基于xml(你自己的结构)的对象。不是吗? – abatishchev 2010-11-09 15:22:58

回答

5
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + 
    "<CatalogProducts>" + 
     "<CatalogProduct Name=\"MyName1\" Version=\"1.1.0\"/>" + 
     "<CatalogProduct Name=\"MyName2\" Version=\"1.1.0\"/>" + 
    "</CatalogProducts>"; 
var document = XDocument.Parse(xml); 

IEnumerable<CatalogProduct> catalogProducts = 
     from c in productsXml.Descendants("CatalogProduct") 
     select new CatalogProduct 
     { 
      Name = c.Attribute("Name").Value, 
      Version = c.Attribute("Version").Value 
     }; 
+0

嗨克里斯,我不能使用XmlSerializer对象,所以我可以添加属性到我的XML文档,他们将automatiaclly设置为我的c#对象中的属性? – Bob 2010-11-09 15:24:19

+0

是的,这需要使用序列化器来序列化和反序列化。这种解决方案是假定xml未被序列化的,解析xml文档的Linq to Xml方式。 – 2010-11-09 15:46:44

1

的规范方法是使用两次xsd.exe工具。首先,从您的示例XML创建模式,如下所示:

xsd.exe file.xml将生成file.xsd。

然后:

xsd.exe /c file.xsd会产生file.cs.

File.cs将成为您可以反序列化您的XML的对象,使用您可以在此轻松找到的任何一种技术,例如, this

+0

嗨,杰西,我已经有我的CatalogProduct对象。我只需要知道代码来使用LINQ to XML或任何其他方法获取XML中的特定元素,然后序列化。我不想使用xsd.exe文件。谢谢 – Bob 2010-11-09 15:21:37

0

假设你CatalogProduct物体看起来是这样的:

public class CatalogProduct { 
     public string Name; 
     public string Version; 
    } 

我想的LINQ to XML将是最简单和最快的方式为您

var cps1 = new[] { new CatalogProduct { Name = "Name 1", Version = "Version 1" }, 
       new CatalogProduct { Name = "Name 2", Version = "Version 2" } }; 

var xml = new XElement("CatalogProducts", 
      from c in cps1 
      select new XElement("CatalogProduct", 
       new XAttribute("Name", c.Name), 
       new XAttribute("Version", c.Version))); 

    // Use the following to deserialize you objects 
var cps2 = xml.Elements("CatalogProduct").Select(x => 
    new CatalogProduct { 
     Name = (string)x.Attribute("Name"), 
     Version = (string)x.Attribute("Version") }).ToArray(); 

请注意,.NET提供了真正的对象图序列化,我没有显示

4

只是为了您的信息,这里是如何真正的序列化和反序列化对象的示例:

private CatalogProduct Load() 
{ 
    var serializer = new XmlSerializer(typeof(CatalogProduct)); 
    using (var xmlReader = new XmlTextReader("CatalogProduct.xml")) 
    { 
     if (serializer.CanDeserialize(xmlReader)) 
     { 
      return serializer.Deserialize(xmlReader) as CatalogProduct; 
     } 
    } 
} 

private void Save(CatalogProduct cp) 
{ 
    using (var fileStream = new FileStream("CatalogProduct.xml", FileMode.Create)) 
    { 
     var serializer = new XmlSerializer(typeof(CatalogProduct)); 
     serializer.Serialize(fileStream, cp); 
    } 
}