Reputation: 3241
I have the following XML, and I only want to deserialize the streams of Product1, what would be the syntax in C#? Thanks. I couldn't find any documentations online.
<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>
Upvotes: 2
Views: 3872
Reputation: 1039398
You could use XDocument and XPath to filter:
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);
}
}
}
Upvotes: 3
Reputation: 15722
I will not write your code. Have a look at http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx and write a class which might fit your needs, and serialize it. Get familiar with the attributes used to control serialization and tune your class to be serialized the way your example looks like. Then your are able to use it for deserialization too.
Of course there are other options to read the data from the XML, but I'll not document all of them. Obviously you could also read the data "by hand" using , XmlDocument, XDocument, XmlReader, ... or whatever fits your requirements.
Upvotes: 2
Reputation: 24027
You can't really do selective deserialization, but you can filter the results after it's been deserialized to something like an XDocument
object. 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;
Upvotes: 1
Reputation: 19608
Did you checked this? XmlSerializer.Deserialize Method (Stream) on MSDN
Upvotes: 1