1

I am trying to get a node out of an XML file and having a hell of a time. XML:

<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>26.0</apiVersion>
    <label>aaaWsPage2</label>
    <description></description>
    <rffolder>Robert Test</rffolder>
</ApexPage>

I tried the following code:

var doc = new XmlDocument();
doc.Load(@"c:\test.xml");

var mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("ns1", @"http://soap.sforce.com/2006/04/metadata");

XmlElement root = doc.DocumentElement;

string query = @"/ns1:ApexClass/ns1:rffolder";
var xmlNode = root.SelectSingleNode(query);
if (xmlNode != null)
   Console.WriteLine(xmlNode.InnerXml);

xmlNode is always null or I get an exception on .SelectSingleNode. What am I missing here?

2
  • Any reason you are not using Linq to XML? the syntax is much easier to use. Commented Aug 5, 2013 at 22:23
  • @Jay Care to show me an example? I've never used Linq with XML. Commented Aug 5, 2013 at 22:26

5 Answers 5

4

I always find Linq To Xml easier to use

var xDoc = XDocument.Load(fname);
XNamespace ns = "http://soap.sforce.com/2006/04/metadata";

var folder = xDoc.Root.Element(ns + "rffolder").Value;
Sign up to request clarification or add additional context in comments.

Comments

2

can you please try this?

XmlElement root = doc.DocumentElement.SelectSingleNode(@"//ns1:ApexClass/ns1:rffolder) as XmlElement;

Comments

1

You can use LinqToXml

 var node = XElement.Load(@"C:\Test.xml")
                    .Element(XName.Get("rffolder","http://soap.sforce.com/2006/04/metadata"));

Comments

1

If you don't want to use Linq2Xml:

first of all, in the XML the root is called ApexPage, not ApexClass, and you forgot to pass the XmlNamespaceManager to the SelectSingleNode.

So:

string query = @"/ns1:ApexPage/ns1:rffolder";
var xmlNode = root.SelectSingleNode(query, mgr);

Should work as well

Comments

0

Try changing your query string to:

string query = "//ns1:ApexClass/ns1:rffolder";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.