【问题标题】:Very simple XML reading in C#.NETC#.NET 中非常简单的 XML 读取
【发布时间】:2013-12-09 17:17:59
【问题描述】:

我想读取以下 XML 文件:

Words.xml:

<?xml version="1.0" encoding="utf-8" ?>
<words>
  <word>Bat</word>
  <word>Dog</word>
  <word>Car</word>
</words>

..使用 XDocument。我不断收到此代码的“非空白字符无法添加到内容”错误:

XDocument doc = new XDocument("words.xml");
foreach (XElement element in doc.Descendants("word"))
{
   Console.WriteLine(element.Value);
}

【问题讨论】:

    标签: c# .net xml linq-to-xml


    【解决方案1】:

    你需要像这样加载文档:

    XDocument doc = XDocument.Load("words.xml");
    

    您的原始代码失败的原因是您使用的是 XDocument (Object[]) constructor,它通常需要 XElement 对象列表,例如:

    var doc = new XDocument(new XElement("Root"));
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 2010-09-07
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    相关资源
    最近更新 更多