Subscribe

RSS Feed (xml)

Get XML Nodes in a Specific XML Namespace

Many XML documents contain nodes from more than one namespace. For example, an XML document that represents a scientific article might use a separate type of markup for denoting math equations and vector diagrams, or an XML document with information about a purchase order might aggregate client and order information with a shipping record. Similarly, an XML document that represents a business-to-business transaction might include portions from both companies, written in separate markup languages.

A common task in XML programming is to retrieve the elements that are found in a specific namespace. You can perform this task with the overloaded version of the XmlDocument.GetElementsByTagName method that requires a namespace name. You can use this method to find tags by name, or to find all the tags in the specified namespace if you supply an asterisk for the tag name parameter.

As an example, consider the following compound XML document that includes order and client information, in two different namespaces (http://mycompany/OrderML and http://mycompany/ClientML).

<?xml version="1.0" ?>
<ord:order xmlns:ord="http://mycompany/OrderML"
 xmlns:cli="http://mycompany/ClientML">

  <cli:client>
    <cli:firstName>Sally</cli:firstName>
    <cli:lastName>Sergeyeva</cli:lastName>
  </cli:client>

  <ord:orderItem itemNumber="3211"/>
  <ord:orderItem itemNumber="1155"/>

</ord:order>

Here's a simple console application that selects all the tags in the http://mycompany/OrderML namespace:

using System;
using System.Xml;

public class SelectNodesByNamespace {

    private static void Main() {

        // Load the document.
        XmlDocument doc = new XmlDocument();
        doc.Load("Order.xml");

        // Retrieve all order tags.
        XmlNodeList matches = doc.GetElementsByTagName("*",
          "http://mycompany/OrderML");

        // Display all the information.
        Console.WriteLine("Element \tAttributes");
        Console.WriteLine("******* \t**********");

        foreach (XmlNode node in matches) {

            Console.Write(node.Name + "\t");
            foreach (XmlAttribute attribute in node.Attributes) {
                Console.Write(attribute.Value + "  ");
            }
            Console.WriteLine();
        }
 
        Console.ReadLine();
    }
}

The output of this program is as follows:

Element         Attributes
*******         **********
ord:order       http://mycompany/OrderML  http://mycompany/ClientML
ord:orderItem   3211
ord:orderItem   1155

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail