Channels ▼
RSS

Web Development

Comparing LINQ-to-XML with XPath


Using Namespaces

XML documents support namespaces. For example, if you add the following namespace to the XML file in Listing One (right after the <xml> tag -- both are shown), you need to include the namespace in both your LINQ-to-XML and your XPath queries.

<?xml version="1.0" encoding="utf-8"?>
<jack:Blackjack xmlns:jack="http://www.blackjack.com">

The XML in Listing Two shows the proper placement of the namespace jack added to the XML from Listing One. The code in Listing Three incorporates the namespace in the LINQ-to-XML to obtain the net amount won (or lost) from the XML file in Listing One. The second half of the listing uses the XPathSelectElement method and an XPath query to obtain the same value.

<?xml version="1.0" encoding="utf-8"?>
<jack:Blackjack xmlns:jack="http://www.blackjack.com">
  <jack:Player Name="Player 1">
    <jack:Statistics>
      <jack:AverageAmountLost>-28.125</jack:AverageAmountLost>
      <jack:AverageAmountWon>30.681818181818183</jack:AverageAmountWon>
      <jack:Blackjacks>1</jack:Blackjacks>
      <jack:Losses>8</jack:Losses>44
      <jack:NetAverageWinLoss>5.9210526315789478</jack:NetAverageWinLoss>
      <jack:NetWinLoss>112.5</jack:NetWinLoss>
      <jack:PercentageOfBlackJacks>0.041666666666666664</jack:
PercentageOfBlackJacks>
      <jack:PercentageOfLosses>33.333333333333329</jack:PercentageOfLosses>
      <jack:PercentageOfPushes>16.666666666666664</jack:PercentageOfPushes>
      <jack:PercentageOfWins>45.833333333333329</jack:PercentageOfWins>
      <jack:Pushes>4</jack:Pushes>
      <jack:Surrenders>1</jack:Surrenders>
      <jack:TotalAmountLost>-225</jack:TotalAmountLost>
      <jack:TotalAmountWon>337.5</jack:TotalAmountWon>
      <jack:Wins>11</jack:Wins>
    </jack:Statistics>
  </jack:Player>
</jack:Blackjack>
Listing Two: The XML from Listing One with the Namespace jack Added

using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
  private static void UseNamespace()
  {
    const string filename = "..\\..\\CurrentStatsWithNamespace.xml";
    XDocument doc = XDocument.Load(filename);
    XNamespace jack = "http://www.blackjack.com";

    XElement winLoss1 = doc.Element(jack + "Blackjack")
      .Element(jack + "Player").Element (
      jack + "Statistics").Element(jack + "NetWinLoss");
    Console.WriteLine(winLoss1);
    Console.ReadLine();
    XmlReader reader = XmlReader.Create(filename);
    XElement root = XElement.Load(reader);
    XmlNameTable table = reader.NameTable;
    XmlNamespaceManager manager = new XmlNamespaceManager(table);
manager.AddNamespace("jack", "http://www.blackjack.com");
    XElement winLoss2 =
      doc.XPathSelectElement(
      "./jack:Blackjack/jack:Player/jack:Statistics/jack:NetWinLoss",
manager);
    Console.WriteLine(winLoss2);
    Console.ReadLine();
}
Listing Three: The Main Function Uses LINQ to XML and a Namespace to Obtain a Value, and an Equivalent XPath Query to Obtain the Same Value

In the example, an XmlReader was created from the XML file. The root XElement was obtained from the reader, followed by the Nametable. The Nametable is an instance of the System.Xml.Nametable class, and it contains the atomized names of the elements and attributes of the XML document. If a name appears multiple times in an XML document, it is stored only once in a Nametable, as a Common Language Runtime (CLR) object. Such storage permits object comparisons on these elements and attributes rather than a much more expensive string comparison. (This is managed for you.)

Next, the table is used to create an XmlNamespaceManager and the desired XML namespace string is added to the manager. Finally, the XmlNamespaceManager is passed as an argument to the XPathSelectElement method. The XPath query is "./jack:Blackjack/jack:Player/jack:Statistics/jack:NetWinLoss". The subpath "jack:" demonstrates how to incorporate the namespace in the XPath query.

Our examples use the XPath support provided by LINQ-to-XML in the System.Xml.Linq namespace. XPath support is provided in System.Xml.XPath too, and you would use different classes and behaviors if you were to use that approach. As an exercise, if you are interested, you can experiment by implementing the equivalent behaviors using the capabilities of the XPath namespace.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 
Dr. Dobb's TV