开发者

How to read xml node value

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>


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜