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>
3
  • 3
    How are you trying to read the value? Care to give a code sample? Commented May 12, 2011 at 6:31
  • here you go , matches does not bring anything. XmlDocument xdoc = new XmlDocument(); xdoc.Load(file); XmlNodeList matches = xdoc.SelectNodes("//First"); Commented May 12, 2011 at 6:42
  • Please update your question with any additional info you have. Commented May 12, 2011 at 6:43

3 Answers 3

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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);
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.

Comments

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.

2 Comments

how do I pass a filename instead of text?
@melspring: XElement xml = XElement.Load(filepath);

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.