C# 使用 XElement 解析 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9090033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:51:44  来源:igfitidea点击:

XML parsing using XElement

c#xmlxelement

提问by joelc

Can't seem to find how to appropriately parse this using XElement:

似乎无法找到如何使用 XElement 适当地解析它:

<messages>
  <message subclass="a" context="d" key="g">
  <message subclass="b" context="e" key="h">
  <message subclass="c" context="f" key="i">
</messages>

I'd like to get this out to a List where is three strings subclass, context, key.

我想把它放到一个列表中,其中三个字符串的子类、上下文、键。

采纳答案by Anthony Pegram

Your input is not valid XML, it's missing closing tags on the inner message elements. But assuming the format was valid, you could parse out your structure as in:

您的输入不是有效的 XML,它缺少内部消息元素上的结束标记。但假设格式有效,您可以解析出您的结构,如下所示:

string xml = @"<messages> 
                  <message subclass=""a"" context=""d"" key=""g""/> 
                  <message subclass=""b"" context=""e"" key=""h""/> 
                  <message subclass=""c"" context=""f"" key=""i""/> 
               </messages>";

var messagesElement = XElement.Parse(xml);
var messagesList = (from message in messagesElement.Elements("message")
                   select new 
                    {
                        Subclass = message.Attribute("subclass").Value,
                        Context = message.Attribute("context").Value,
                        Key = message.Attribute("key").Value
                    }).ToList();

You can also use XDocumentfor a full XML document, and use the Loadmethod instead of Parseif you were using an XML file or a stream, for example. Additionally, you can select into a concrete class if you have one defined. Given a class definition of

例如,您还可以使用XDocument完整的 XML 文档,并使用该Load方法而不是Parse使用 XML 文件或流。此外,如果您定义了一个具体类,您可以选择进入一个具体类。给定一个类定义

class Message 
{
    public string Subclass { get; set; }
    public string Context { get; set; } 
    public string Key { get; set; }
}

You could use select new Messagein the query, and the result would be a List<Message>, whereas right now it is a list of an anonymous type.

您可以select new Message在查询中使用,结果将是 a List<Message>,而现在它是一个匿名类型的列表。

回答by Priyanka Arora

In XElement, Descendants()is the only method I use and it gives the results using LINQ.

XElement,Descendants()是我使用的唯一方法,它使用 LINQ 给出结果。

var abc = doc.Descendants()
    .Where(t => t.Name.LocalName == "pqr")
    .Select(t => t.Value)
    .FirstOrDefault();