Friday, December 9, 2011

SelectSingleNode / SelectNodes

The selectSingleNode method returns a Node object for the first descendant node to match the specified pattern. The one parameter of this method is an XSL pattern query. If no match is made, it returns null. This method is similar to theselectNodes method, but returns only the first node to match the pattern rather than all of them.



// Load the document and set the root element.
XmlDocument doc = new XmlDocument();
doc.Load("bookstore.xml");
XmlNode root = doc.DocumentElement;

// Add the namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");

// Select and display the first node in which the author's 
// last name is Kingsolver.
XmlNode node = root.SelectSingleNode(
    "descendant::bk:book[bk:author/bk:last-name='Kingsolver']", nsmgr);
Console.WriteLine(node.InnerXml);
----------------
The primary means of reading and writing in C# 2.0 is done through the XmlDocument class. You can load most of your settings directly into the XmlDocument through the XmlReader it accepts.

Loading XML Directly

XmlDocument document = new XmlDocument();
document.LoadXml("");

Loading XML From a File

XmlDocument document = new XmlDocument();
document.Load(@"C:\Path\To\xmldoc.xml");
// Or using an XmlReader/XmlTextReader
XmlReader reader = XmlReader.Create(@"C:\Path\To\xmldoc.xml");
document.Load(reader);
I find the easiest/fastest way to read an XML document is by using XPath.

Reading an XML Document using XPath (Using XmlDocument which allows us to edit)

XmlDocument document = new XmlDocument();
document.LoadXml("");
// Select a single node
XmlNode node = document.SelectSingleNode("/People/Person[@Name = 'Nick']");
// Select a list of nodes
XmlNodeList nodes = document.SelectNodes("/People/Person");
If you need to work with XSD documents to validate an XML document you can use this.

Validating XML Documents against XSD Schemas

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
XmlReader reader = XmlReader.Create(pathToXml, settings);
XmlDocument document = new XmlDocument();
try {
    document.Load(reader);
} catch (XmlSchemaValidationException ex) { Trace.WriteLine(ex.Message); }

Validating XML against XSD at each Node (UPDATE 1)

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
XmlReader reader = XmlReader.Create(pathToXml, settings);
while (reader.Read()) { }
private void settings_ValidationEventHandler(object sender, ValidationEventArgs args)
{
    // e.Message, e.Severity (warning, error), e.Error
    // or you can access the reader if you have access to it
    // reader.LineNumber, reader.LinePosition.. etc
}

Writing an XML Document (manually)

XmlWriter writer = XmlWriter.Create(pathToOutput);
writer.WriteStartDocument();
writer.WriteStartElement("People");

writer.WriteStartElement("Person");
writer.WriteAttributeString("Name", "Nick");
writer.WriteEndElement();

writer.WriteStartElement("Person");
writer.WriteStartAttribute("Name");
writer.WriteValue("Nick");
writer.WriteEndAttribute();
writer.WriteEndElement();

writer.WriteEndElement();
writer.WriteEndDocument();

writer.Flush();
(UPDATE 1)
In .NET 3.5, you use XDocument to perform similar tasks. The difference however is you have the advantage of performing Linq Queries to select the exact data you need. With the addition of object initializers you can create a query that even returns objects of your own definition right in the query itself.
    XDocument doc = XDocument.Load(pathToXml);
    List<Person> people = (from xnode in xdoc.Element("People").Elements("Person")
                       select new Person
                       {
                           Name = xnode.Attribute("Name").Value
                       }).ToList();
(UPDATE 2)
A nice way in .NET 3.5 is to use XDocument to create XML is below. This makes the code appear in a similar pattern to the desired output.
XDocument doc =
        new XDocument(
              new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty),
              new XComment("Xml Document"),
              new XElement("catalog",
                    new XElement("book",
                          new XAttribute("id", "bk001"),
                                new XElement("title", "Book Title")
                    )
              )
        );
creates


  < span=""> id="bk001"
    </span><span class="pln" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; ">Book Title</span><span class="tag" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; color: rgb(128, 0, 0); ">
  

All else fails, you can check out this MSDN article that has many examples that I've discussed here and more. http://msdn.microsoft.com/en-us/library/aa468556.aspx
-----------------------------------------