【问题标题】:Reading an XML File with .NET使用 .NET 读取 XML 文件
【发布时间】:2010-04-02 04:58:47
【问题描述】:

我是 xml 新手,无法找到在标签之间获取内容的方法。 我的 XML 文件是

<?xml version="1.0" encoding="utf-8"?>
<block1>
  <file name="c:\w0.xml">
    <word>Text</word>
    <number>67</number>
   </file>
  <file name="c:\w1.xml">
    <word>Text</word>
    <number>67</number>
  </file>
  <file name="c:\w2.xml">
    <word>Text</word>
    <number>67</number>
  </file>
</block1>

【问题讨论】:

  • 请展示您的尝试。

标签: c# .net xml


【解决方案1】:

LINQ to XML 是一个很好的起点。考虑以下代码来解析您的 XML。

string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> 
<block1> 
  <file name=""c:\w0.xml""> 
    <word>Text</word> 
    <number>67</number> 
   </file> 
  <file name=""c:\w1.xml""> 
    <word>Text</word> 
    <number>67</number> 
  </file> 
  <file name=""c:\w2.xml""> 
    <word>Text</word> 
    <number>67</number> 
  </file> 
</block1>";

XDocument document = XDocument.Parse(xml);

var block = from file in document.Descendants("file")
            select new
            {
                Name = file.Attribute ("name").Value,
                Word = file.Element("word").Value,
                Number = (int)file.Element("number")
            };

foreach (var file in block)
{
    Console.WriteLine("{0}\t{1}\t{2}", file.Name, file.Word, file.Number );
}

当然,您可以使用 XDocument.Load 直接从文件加载 XML,而不是使用 Parse 来读取 XML 字符串。 XDocument 位于 System.Xml.Linq 命名空间中。坦率地说,我将从那里开始,但在 System.Xml 命名空间(XmlReader.Create 等)中还有其他使用 XML 的选项。

【讨论】:

  • @Anthony:不是XmlTextReaderXmlReader.Create.
  • 谢谢,约翰。去展示我所知道的。自从 LINQ 出现以来,我已经(几乎)忘记了有关其他方法的所有内容!非常悲惨。
【解决方案2】:

您需要使用 XML 查询语言。如果您使用的是.Net 3.5,我会推荐LINQ to XML;如果您使用的是早期版本,我会推荐LINQ to XML。 XPath 具有成为行业标准的优势,但在我看来,LINQ to XML 是一个更“干净”的 API。

How to query XML with an XPath expression by using Visual C# - 使用 XPath 的教程

LINQ to XML Video Tutorial

MSDN XPath Examples - 来自 XPath 参考

Location Paths - 例如包含 text() 函数。

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 2012-09-09
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多