2010-11-09 157 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); 
    } 
}