如何读取xml节点值

时间:2011-05-12 06:30:58

标签: .net c#-4.0

我有一个xml文件,我很难在c#中读取值“我的名字” 有人可以帮忙吗?

<?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 个答案:

答案 0 :(得分:1)

最有可能的是,在尝试选择节点之前,您忘了定义命名空间。

有关详细信息,请参阅XML: Object reference not set to an instance of an objectHow to select xml root node when root node has attribute?

答案 1 :(得分:1)

您可以使用XPathSelectElement方法:

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

答案 2 :(得分:1)

这是一种方法:

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;

这只会为您提供一个 family 类型的元素和一个类型的元素。