Reputation: 13
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>
Upvotes: 1
Views: 543
Reputation: 3720
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.
Upvotes: 1
Reputation: 1039468
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);
}
}
}
Upvotes: 1
Reputation: 174457
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.
Upvotes: 1