1

I'm have an xml file and am struggling to read value "my name" in c# can anyone help?

<?xml version="1.0" encoding="UTF-8" ?> 
<doc:SomeReport xsi:schemaLocation="urn:tes:doc:Fsur.0.97 C:\Documents%20and%20Settings\rty0403\Desktop\Smaple%20Sampling%20Schemas\Testdoc.doc.0.97.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bie3="urn:tes:data:CommonAggregates:0.97" xmlns:bie1="urn:tes:data:SampleAggregates:0.97" xmlns:doc="urn:tes:doc:Fsur.0.97">
  <doc:family>
    <doc:first>my name</doc:first> 
  </doc:family>
</doc:SomeReport>
Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
melspring
  • 13
  • 2

3 Answers3

1

Most probably, you forgot to define the namespace before trying to select the node.

See XML: Object reference not set to an instance of an object or How to select xml root node when root node has attribute? for more info.

Community
  • 1
  • 1
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

You could use the XPathSelectElement method:

using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

class Program
{
    static void Main()
    {
        using (var reader = XmlReader.Create("test.xml"))
        {
            var doc = XDocument.Load(reader);
            var nameTable = reader.NameTable;
            var namespaceManager = new XmlNamespaceManager(nameTable);
            namespaceManager.AddNamespace("doc", "urn:tes:doc:Fsur.0.97");
            var first = doc.XPathSelectElement("//doc:first", namespaceManager);
            Console.WriteLine(first.Value);
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks Darin that works fine!!, just wondering whats the difference between using XDocument and XMLDocumnet like below XmlDocument xdoc = new XmlDocument(); xdoc.Load(file); XmlNamespaceManager man = new XmlNamespaceManager(xdoc.NameTable); man.AddNamespace("doc", "urn:tes:doc:Fsur.0.97"); XmlNodeList matches = xdoc.SelectNodes("//doc:first", man); – melspring May 13 '11 at 00:44
1

Here's one way to do it:

XElement xml = XElement.Load(fileName); // load the desired xml file
XNamespace aw = "urn:tes:doc:Fsur.0.97"; // this is the namespace in your xml

var firstName = xml.Element(aw + "family").Element(aw + "first").Value;

This will only get you one element of type family and one element of type first.

alex
  • 3,710
  • 32
  • 44