Question

I have xml files which look like this:

<?xml version="1.0" encoding="utf-8"?>
<record id="177" restricted="false">
    <type>record type</type>
    <startdate>2000-10-10</startdate>
    <enddate>2014-02-01</enddate>
    <titles>
        <title xml:lang="en" type="main">Main title</title>
        <!-- only one title element with type main -->
        <title xml:lang="de" type="official">German title</title>
        <!-- can have more titles of type official -->
    </titles>
    <description>description of the record</description>
    <categories>
        <category id="122">
            <name>category name</name>
            <description>category description</description>
        </category>
        <!-- can have more categories -->
    </categories>
    <tags>
        <tag id="5434">
            <name>tag name</name>
            <description>tag description</description>
        </tag>
        <!-- can have more tags -->
    </tags>
</record>

How do I select the data from these xml files using LINQ, or should I use something else?

Was it helpful?

Solution

You can load xml into XDocument objects using either the Load() method for files, or the Parse() method for strings:

var doc = XDocument.Load("your-file.xml");
// OR
var doc = XDocument.Parse(yourXmlString);

Then you can access the data using LINQ:

var titles =
    from title in doc.XPathSelectElements("//title")
    where title.Attribute("type").Value == "official"
    select title.Value;

OTHER TIPS

Was searching for examples of Xmlserializer and found this: How to Deserialize XML document So why not to try. I did Ctrl+C and Edit -> Paste Special -> Paste XML As Classes in Visual Studio 2013 and... Whoa I got all the classes generated. One condition target framework must be 4.5 and this function is available from Visual Studio 2012+ (as stated in that post)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top