尝试使用C#读取特定的Xml值

msc*_*msc 0 c# xml visual-studio

我是C#的新手.请帮我.

data.xml中

<?xml version="1.0" standalone="yes"?>
<DataSet1 xmlns="http://tempuri.org/DataSet1.xsd">
  <Language>
    <Id>001</Id>
    <English>"Welcome to India"</English>
    <German>"Willkommen in Indien"</German>
  </Language>
</DataSet1>
Run Code Online (Sandbox Code Playgroud)

如何阅读Id使用C#Xml的价值?我是C#的新手.请帮我.

我的努力:

XmlDocument doc = new XmlDocument();
XmlReader reader = XmlReader.Create(@"D:\data.xml");

while(reader.Read())
{
    reader.MoveToContent();
    if (reader.IsStartElement("DataSet1"))
    {
        reader.ReadToDescendant("Language");

        string str2 = reader.Name.ToString();
        MessageBox.Show(str2);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

我强烈建议您使用LINQ to XML,这是一个比API更简单的API XmlDocument,并且具有出色的命名空间支持.以下是Id使用LINQ to XML 获取值的示例:

using System;
using System.Xml.Linq;          

public class Program
{
    public static void Main()
    {
        XDocument doc = XDocument.Load("test.xml");
        XNamespace ns = "http://tempuri.org/DataSet1.xsd";

        string id = doc.Root           // From the root...
            .Element(ns + "Language")  // select the Language direct child...
            .Element(ns + "Id")        // and the Id child of that...
            .Value;                    // and then take the text value
        Console.WriteLine(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,如果您的XML不只是一个Language元素,您需要选择正确的元素,等等.您应该阅读LINQ to XML文档以获取更多信息.