Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nodes with XPath in C#?

Tags:

c#

.net

xpath

Simple question, I just want to select the text from the <Template> tag. Here's what I have, but the Xpath doesn't match anything.

public static void TestXPath()
{
    string xmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
    xmlText += "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\">";
    xmlText += "<Template>Normal</Template>  <TotalTime>1</TotalTime>  <Pages>1</Pages>  <Words>6</Words>";
    xmlText += "</Properties>";

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(new System.IO.StringReader(xmlText));

    foreach (XmlNode node in xmlDoc.SelectNodes("//Template"))
    {
        Console.WriteLine("{0}: {1}", node.Name, node.InnerText);
    }
}
like image 274
Joe Avatar asked Jul 08 '09 19:07

Joe


People also ask

What is node set in XPath?

A node set is a set of nodes. When you write an XPath expression to return one or more nodes, you call these nodes a node set. For example, if you use the following expression to return a node called title , you will have a set of nodes all called title (assuming there's more than one record).


1 Answers

You need to use an XmlNamespaceManager because the Template element is in a namespace:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new System.IO.StringReader(xmlText));
XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace("ns", 
    "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties");

foreach (XmlNode node in xmlDoc.SelectNodes("//ns:Template", manager))
{
    Console.WriteLine("{0}: {1}", node.Name, node.InnerText);
}
like image 137
Jon Skeet Avatar answered Sep 21 '22 16:09

Jon Skeet