【问题标题】:Get all attributes from the xml file c#从xml文件c#中获取所有属性
【发布时间】:2022-01-13 03:52:42
【问题描述】:

有没有办法从 xml 文件中获取所有属性? XML 文件:


<xml>
<level1>
<login Val=“true”><\login>
<inval>hello<\inval>
<\level1>
<level2 name=“Lara”>
<input place =“VKK”> teddy string <\input>
<\level2>

我正在寻找包含的 xmlatributecollection 真值 名称劳拉 放置VKK

也可以使用子元素(上面的元素

但我希望它会返回: 名称劳拉 放置VKK

有可能吗?请分享想法。谢谢

【问题讨论】:

  • 这能回答你的问题吗? Get all attributes in XML
  • 是的,我试过了,但在我的情况下可以工作
  • 出了什么问题?
  • 刚刚通过添加更多细节来阐述问题

标签: c# xml attributes


【解决方案1】:

首先,您的 xml 在我看来并不正确,无论如何,我们假设它是这样的:

string xml = @"
<xml>
<level1>
    <login Val=""true""></login>
    <inval>hello</inval>
</level1>
<level2 name=""Lara"">
    <input place=""VKK""> teddy string </input>
</level2>
</xml>";

您可以像这样获取具有相应名称和值的所有属性:

using System.Xml.Linq;

var doc = XDocument.Parse(xml);
var attributes = doc.Descendants()
                 .SelectMany(x => x.Attributes())
                 .ToDictionary(x => x.Name.LocalName, x => (string)x);

结果将是一个带有值的字典:

Key Value
Val true
name Lara
place VKK

DotNetFiddle 示例:https://dotnetfiddle.net/zBbM3Y

【讨论】:

  • 谢谢!在我的情况下,它也有重复的键,所以当我尝试上述建议的方式时,它会说“已经添加了具有相同键的项目”
  • @Lara 在这种情况下,您可以使用不同的数据结构,例如 List&lt;MyAttributes&gt;(),通过构造该列表而不是使用 ToDictionary()
【解决方案2】:

您可以为此目的使用 XDocument 类

using System.Xml.Linq

XDocument 类包含有效 XML 文档所需的信息,其中包括 XML 声明、处理指令和 cmets。

如果您需要 XDocument 类提供的特定功能,您只需创建 XDocument 对象。

var path="";//your xml file path
var xDocLoad = XDocument.Load(path);

var allAttributes = xDocLoad.Descendants()
                 .SelectMany(x => x.Attributes())
                 .ToDictionary(x => x.Name.LocalName, x => (string)x);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2014-05-30
    • 1970-01-01
    相关资源
    最近更新 更多