Searching an XML Document Node Tree

If there is one area where the XmlDocument API is thin, it is in providing the ability to search an XmlDocument. There are several methods that the XmlDocument does not support since the .NET Compact Framework lacks support for XPath or DTDs. On the desktop .NET Framework, the methods SelectNode and SelectSingleNode accept XPath query strings as parameters.

Also, the GetElementById method, which searches the document for the element with the specified ID, is not supported, because there is no DTD support. This deserves an explanation. An element's ID is a string value of a specific attribute. An attribute is specified as the special ID attribute in the DTD. Since the .NET Compact Framework does not support DTDs, there is no way to figure out which attribute is the special ID attribute.

The XmlDocument and XmlElement classes provide the GetElementsByTagName method to allow searching the document for an element by its name. When called on an XmlDocument object, this method retrieves all XmlElements with a specified name within the entire document. When called on an XmlElement, it finds all elements below the current element. Listing 11.16 shows how to use GetElementsByTagName.

Listing 11.16.
C#
public static void Main()
{
  XmlDocument doc = new XmlDocument();
  StreamReader s = new StreamReader("input.xml", Encoding.UTF8);
  doc.Load(s);
  s.Close();

  XmlNodeList authors = doc.GetElementsByTagName("Author");
  foreach(XmlElement author in authors)
  {
    if(author.GetAttribute("Name") == "John Doe")
    {
      XmlNodeList books = doc.GetElementsByTagName("Book");
      foreach(XmlElement book in books)
      {
         MessageBox.Show(book.FirstChild.InnerText);
      }
    }
  }
}

VB
Sub Main()
  Dim doc As New XmlDocument
  Dim s As New StreamReader("input.xml", Encoding.UTF8)

  doc.Load(s)
  s.Close()

  Dim authors As XmlNodeList
  authors = doc.GetElementsByTagName("Author")

  For Each author As XmlElement In authors
    If author.GetAttribute("Name") = "John Doe" Then
      Dim books As XmlNodeList
      books = doc.GetElementsByTagName("Book")

      For Each book As XmlElement In books
        MessageBox.Show(book.FirstChild.InnerText)
      Next
    End If
  Next
End Sub

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.147.77