Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



XLinq'n in the new world - Structure Modification comparisons with Xml/XPath

Originally this series was meant to be titled 'Any thing you can do I can do better', but to be honest after writing the Xml/XPath examples I realized the XLinq is really no better per say than Xml/XPath.  However, what XLinq does bring to the table that Xml/XPath does not:

  • Does not need to use the XPath query syntax
  • Reads like English (mostly) when creating queries
  • Lower barrier to entry for someone new to Xml (my opinion)

For Part 1 of this series check here
For Part 2 of this series check here

In Part 3 of this little mini series we will examine some common data creation scenario's and how XLinq's syntax compares to that of standard Xml/XPath access.  In general will we review how to modify the structure of an existing Xml document.

Before I get started I will show you a sample of the XML document I am using.

<?xml version='1.0'?>
<root>
  <system>
    <list>
      <subscribers>
        <subscriber Type="Random">
          <id>63425813</id>
          <Email__Address>FakeAddress@comcast.net</Email__Address>
          <EmailType>HTML</EmailType>
          <Status>InActive</Status>
          <First__Name>RAY</First__Name>
          <Last__Name>Bob</Last__Name>
          <PIN__Code>NaN</PIN__Code>
          <PIPIN>33232</PIPIN>
          <UID>418444</UID>
          <ProgNum>0</ProgNum>
          <Title />
          <Username />
          <Password />
        </subscriber>
      </subscribers>
    </list>
    <list>
      <subscribers>
          <subscriber>
          <id>1271728821</id>
          <Email__Address>FakeAddress@yahoo.com</Email__Address>
          <EmailType>HTML</EmailType>
          <Status>InActive</Status>
          <First__Name>JOHN</First__Name>
          <Last__Name>Foo</Last__Name>
          <PIN__Code>NaN</PIN__Code>
          <PIPIN>1254512</PIPIN>
          <UID>1033488</UID>
          <ProgNum />
          <Title />
          <Username />
          <Password />
        </subscriber>
      </subscribers>
    </list>
  </system>
</root>

Example 1 - Adding a New Node w/ Element

via Xml/XPath

// notice the @ is missing on the status -- this is how u search a node
XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
XmlNodeList xmlNodeList = xmlDocument.SelectNodes( "//list" );

foreach ( XmlElement element in xmlNodeList )
{
    XmlNode newNode = xmlDocument.CreateNode( XmlNodeType.Element, "NewElement", string.Empty );
    XmlAttribute nodeAttribute = xmlDocument.CreateAttribute( "MyAttribute" );
    nodeAttribute.Value = "MyValue";

    newNode.Attributes.Append( nodeAttribute );

    element.AppendChild( newNode );
}

Via XLinq

XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();

IEnumerable item = from doc in xDocument.Descendants( "list" )
                             select doc;

foreach ( XElement xElement in item )
{
    xElement.Add( new XElement( "NewElement",
                                new XAttribute( "MyAttribute", "MyValue" ),
                                new XElement( "ChildElement", "ChildValue")) );
}

//ChildValue

One of the big differences you will notice when trying to add nodes/elements to an existing Xml doc with XLinq vs. Xml/XPath is the that with XLinq it is more 'fluent' then with Xml/XPath.  To add nodes/elements with Xml/XPath you need to create the nodes/elements via the XMLdocument object.

Example 2 - Deleting and Node w/ Elements

via Xml/XPath

// notice the @ is missing on the status -- this is how u search a node
XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
XmlNodeList xmlNodeList = xmlDocument.SelectNodes( "//subscribers/subscriber[Status='InActive']" );

foreach ( XmlElement element in xmlNodeList )
{
    element.RemoveAll();
}

Via XLinq

XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();

IEnumerable< XElement > item = from doc in xDocument.Descendants( "subscriber" )
                               let status = (string) doc.Element( "Status" )
                               where status == "InActive"
                               select doc;

foreach ( XElement xElement in item )
{
    xElement.Remove();
}

Besides the way you navigate to the node/element you would like to remove the syntax to delete/remove the nodes are really no different.  But, again with XLinq you do not need to know XPath in order to navigate to the correct location in the document.

Well, this pretty much wraps up my little mini-series on XLinq'n in the new world.  I hope that in the past 3 posts you have learned a little about how to use XLinq and how it differs from Xml/XPath.

Till next time,



Comments

Dew Drop - May 14, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - May 14, 2008 | Alvin Ashcraft's Morning Dew

# May 14, 2008 10:54 AM

Derik Whittaker said:

Originally this series was meant to be titled &#39;Any thing you can do I can do better&#39;, but to

# May 14, 2008 11:02 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News