Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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,


Posted 05-14-2008 7:21 AM by Derik Whittaker
Filed under: ,

[Advertisement]

Comments

Dew Drop - May 14, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - May 14, 2008 | Alvin Ashcraft's Morning Dew
on 05-14-2008 10:54 AM

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

Derik Whittaker wrote XLinq'n in the new world - Speed comparison with Xml/XPath
on 05-14-2008 11:02 AM

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

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)