TrevorGoodchild
TrevorGoodchild

Reputation: 1060

Select subset of XML

I know this is a very basic question but I'm new to XML and while it seems simple, I can't find a simple answer anywhere. I have an XML document that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<root version="1">
<targets>
    <target type="email">
        <property name="to">[email protected]</property>
    </target>
    <target type="fob"/>
</targets>
<observation uniqueID="00A60D" deviceID="308610ea23">
    <field name="field1">test1</field>
    <field name="field2">test2</field>
</observation>

and I'm trying to either select a subset of that xml, or remove nodes, to get it pared down to:

    <observation uniqueID="00A60D" deviceID="308610ea23">
    <field name="attachments">
        <string>1910.jpg</string>
    </field>
    <field name="field1">test1</field>
    <field name="field2">test2</field>
</observation>

So that I can deserialize it into an object. Any help is greatly appreciated.

Upvotes: 0

Views: 1695

Answers (3)

Nirmal
Nirmal

Reputation: 934

Here is a XML to LINQ Version:

dynamic root= XElement.Load(dataStream).Descendants("root")
                        .Select(element => element.Value).ToArray();

This will give all the root element from the document.And you can access root

Upvotes: 1

Konrad Morawski
Konrad Morawski

Reputation: 8394

XElement root = XElement.Parse("<root version ..." // etc. to parse a string. 
// Use XElement.Load to load a file.

var observations = root.Elements("observation");

It assumes one root (by definition) and possibly multiple observation elements.

Upvotes: 0

Alberto
Alberto

Reputation: 15951

You can use XPath:

string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<root version=\"1\">" +
        "<targets>" +
            "<target type=\"email\">" +
                "<property name=\"to\">[email protected]</property>" +
            "</target>" +
            "<target type=\"fob\"/>" +
        "</targets>" +
        "<observation uniqueID=\"00A60D\" deviceID=\"308610ea23\">" +
            "<field name=\"field1\">test1</field>" +
            "<field name=\"field2\">test2</field>" +
        "</observation>" +
        "</root>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlElement root = doc.DocumentElement;
var observationNode = root.SelectSingleNode("/root/observation");

var observationXml = observationNode.OuterXml;

Upvotes: 1

Related Questions