【问题标题】:How to use LINQ to get data from an XML file?如何使用 LINQ 从 XML 文件中获取数据?
【发布时间】:2014-03-30 09:55:19
【问题描述】:

我有如下所示的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<record id="177" restricted="false">
    <type>record type</type>
    <startdate>2000-10-10</startdate>
    <enddate>2014-02-01</enddate>
    <titles>
        <title xml:lang="en" type="main">Main title</title>
        <!-- only one title element with type main -->
        <title xml:lang="de" type="official">German title</title>
        <!-- can have more titles of type official -->
    </titles>
    <description>description of the record</description>
    <categories>
        <category id="122">
            <name>category name</name>
            <description>category description</description>
        </category>
        <!-- can have more categories -->
    </categories>
    <tags>
        <tag id="5434">
            <name>tag name</name>
            <description>tag description</description>
        </tag>
        <!-- can have more tags -->
    </tags>
</record>

如何使用 LINQ 从这些 xml 文件中选择数据,还是应该使用其他方法?

【问题讨论】:

  • LINQ to XML 是一个不错的选择。你应该试试看。
  • 鉴于您知道架构,我建议您先将其反序列化为对象。然后在 C# 中更容易使用。
  • 请说明您要选择的数据。 XElement class 是当今在 C# 中使用 LINQ 和 XML 的首选方式。
  • @Cupcake 该文件包含更多数据,但我需要此处指定的数据(记录类型、开始日期、结束日期、标题主要和所有翻译、带有 id、名称和描述的类别以及与标签相同)。你有任何例子吗,我知道如何创建 XDocument 并添加带有属性的 XElements,然后将其保存到文件中,但如何以其他方式进行(xml 字符串到 XElemet 和 XDocument)。
  • @Aron 你的意思是使用 XMLFormatter 和 Stream 反序列化它?

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


【解决方案1】:

您可以使用Load() 方法将xml 加载到XDocument 对象中 用于文件,或Parse() 方法用于字符串:

var doc = XDocument.Load("your-file.xml");
// OR
var doc = XDocument.Parse(yourXmlString);

然后您可以使用 LINQ 访问数据:

var titles =
    from title in doc.XPathSelectElements("//title")
    where title.Attribute("type").Value == "official"
    select title.Value;

【讨论】:

  • 这给了我System.NullReferenceExceptiontitle.Attribute("type").Value == "official" 突出显示...
  • 这可能是因为title 节点没有type 属性,因此在尝试对空值调用.Value 时会引发异常。您并没有真正指定要如何检索数据,所以我只是制作了自己的较小的示例 xml 来使用。您可以通过在访问子元素之前检查 null 来解决该问题。等等,等一下,让我再检查一下……
  • 好的,我仔细检查了,我使用了您在问题中的确切 XML 文件,但我没有收到任何 NullReferenceExceptions。如果您在问题中使用的 XML 文件与上述文件不同,并且您遇到异常并且无法弄清楚为什么或如何解决它,那么您应该问另一个问题。
  • 好吧,我的错。我研究了整个 xml 文件,发现了另外两个没有 type 属性但我不需要它们的 &lt;title&gt; 标签。试试doc.XPathSelectElements("/titles/title")
  • 好的,小修复 doc.XPathSelectElements("//titles/title") 并且完美运行,谢谢 XD
【解决方案2】:

正在搜索 Xmlserializer 的示例,发现:How to Deserialize XML document 那么为什么不试试呢。我在 Visual Studio 2013 中执行了 Ctrl+C 和编辑 -> 选择性粘贴 -> 将 XML 粘贴为类,然后……哇,我生成了所有类。一个条件目标框架必须是 4.5,并且此功能可从 Visual Studio 2012+ 获得(如该帖子所述)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 2011-04-13
    • 1970-01-01
    • 2013-11-13
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多