views:

643

answers:

3

Hello everyone,

Suppose I have the following XML document, how to get the element value for a:name (in my sample, the value is Saturday 100)? My confusion is how to deal with the name space. Thanks.

I am using C# and VSTS 2008.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt;
  <s:Body>
    <PollResponse xmlns="http://tempuri.org/"&gt;
       <PollResult xmlns:a="http://schemas.datacontract.org/2004/07/FOO.WCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt;
          <a:name>Saturday 100</a:name>
       </PollResult>
    </PollResponse>
  </s:Body>
</s:Envelope>

thanks in advance, George

+3  A: 

It's easier if you use the LINQ to XML classes. Otherwise namespaces really are annoying.

XNamespace ns = "http://schemas.datacontract.org/2004/07/FOO.WCF";
var doc = XDocument.Load("C:\\test.xml"); 
Console.Write(doc.Descendants(ns + "name").First().Value);

Edit. Using 2.0

XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF");
Console.Write(doc.SelectSingleNode("//a:name", ns).InnerText);
aquinas
Sorry I need to be bound to .Net 2.0. Any solution for this?
George2
Thanks aquinas, your solution works!
George2
+4  A: 

Use System.Xml.XmlTextReader class,

System.Xml.XmlTextReader xr = new XmlTextReader(@"file.xml");
        while (xr.Read())
        {
            if (xr.LocalName == "name" && xr.Prefix == "a")
            {
                xr.Read();
                Console.WriteLine(xr.Value);
            }
        }
adatapost
Thanks adatapost, I prefer to use XPATH since it is more stable and easy to maintain, suppose I may change format of XML request and response in the future.
George2
+3  A: 

XPath is the direct way to get at bits of an XML document in 2.0

XmlDocument xml = new XmlDocument();
xml.Load("file.xml") 
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF");
string name = xml.SelectSingleNode("//a:name", manager).InnerText;
Steve Gilham
Thanks Steve, your solution works!
George2