I recently started learning xml, xpath, xmldocuemtn in c#.
I have an xml as shown bellow..namespaces is confusing me a lot
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Pricing">
</Worksheet>
<Worksheet ss:Name="Order">
</Worksheet>
</Workbook>
Here is my c# code..
XmlDocument doc = new XmlDocument();
doc.Load(ExcelFilePath);
Can you tell me how i can get Worksheet elemet with ss:Name attribute='Pricing'
You have to use XmlNamespaceManager
to provide namespaces:
var namespaceMgr = new XmlNamespaceManager(doc.NameTable);
namespaceMgr.AddNamespace("x", "urn:schemas-microsoft-com:office:spreadsheet");
namespaceMgr.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
var node = doc.SelectSingleNode("//x:Worksheet[@ss:Name='Pricing']", namespaceMgr);
Note that prefixes for namespaces not must match those from XML - the value of namespace counts. So, for example, I've defined ss
as in XML, but default (root) namespace I've named x
- it does not matter as long as its value is the same.
To be more strict, you can change XPath to /x:Workbook/x:Worksheet[@ss:Name='Pricing']
of course.