2011-04-11 36 views
2

我有以下XML,我只想反序列化Product1的流,C#中的語法是什麼?謝謝。我在網上找不到任何文件。XMl解串器在C#

<ArrayOfProductData> 
- <ProductData> 
    <ProductName>product1</ProductName> 
    <ProductID>1</ProductID> 
- <Streams> 
    <productId>1</productId> 
    <name>current stream</name> 
    <id>1</id> 
    </Streams> 
- <Streams> 
    <productId>1</productId> 
    <name>stream 1.1</name> 
    <id>2</id> 
    </Streams> 
    </ProductData> 
- <ProductData> 
    <ProductName>product2</ProductName> 
    <ProductID>2</ProductID> 
- <Streams> 
    <productId>2</productId> 
    <name>current stream</name> 
    <id>1</id> 
    </Streams> 
- <Streams> 
    <productId>2</productId> 
    <name>stream 1.2</name> 
    <id>2</id> 
    </Streams> 
    </ProductData> 
    </ArrayOfProductData> 
+0

你有在地方,那就是做任何反序列化的任何代碼? – RQDQ 2011-04-11 15:27:56

回答

3

你可以使用XDocument和XPath過濾:

using System; 
using System.Linq; 
using System.Xml.Linq; 
using System.Xml.XPath; 

public class ProductStream 
{ 
    public int Id { get; set; } 
    public int ProductId { get; set; } 
    public string Name { get; set; } 
} 

class Program 
{ 
    static void Main() 
    { 
     var streams = XDocument 
      .Load("test.xml") 
      .XPathSelectElements("//ProductData[ProductID='1']/Streams") 
      .Select(s => new ProductStream 
      { 
       Id = int.Parse(s.Element("id").Value), 
       ProductId = int.Parse(s.Element("productId").Value), 
       Name = s.Element("name").Value 
      }); 

     foreach (var stream in streams) 
     { 
      Console.WriteLine(stream.Name); 
     } 
    } 
} 
+0

非常感謝。這是完美的!! – RKM 2011-04-11 17:48:05

1

你真的不能做選擇性的反序列化,但它已經反序列化的東西像一個XDocument對象後,可以篩選結果。 EG:

using System.Xml.Linq; 

XDocument myDoc = XDocument.Load("myfile.xml"); 

var prod1Streams = from e in XDocument.Root.Elements("Streams") 
        where e.Element("productId") != null 
        && e.Element("productId").Value == "1" 
        select e; 
2

我不會寫你的代碼。看看http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx並編寫一個可能適合您的需求的類,並將其序列化。熟悉用於控制序列化的屬性,並按照您的示例的樣子將您的類調整爲序列化。那麼你也可以使用它進行反序列化。

當然,還有其他選項可以從XML讀取數據,但我不會記錄所有這些數據。顯然你也可以使用XmlDocument,XDocument,XmlReader,或者任何符合你的要求的「手動」讀取數據。