gpt4 book ai didi

C# 从 xml 属性中获取值

转载 作者:数据小太阳 更新时间:2023-10-29 01:59:53 24 4
gpt4 key购买 nike

如何使用 C# 以正确的方式获取属性“action”和“filename”的值?

XML:

<?xml version="1.0" encoding="utf-8" ?>
<Config version="1.0.1.1" >
<Items>
<Item action="Create" filename="newtest.xml"/>
<Item action="Update" filename="oldtest.xml"/>
</Items>
</Config>

C#: 我无法获取属性值以及如何在 foreach 循环中获取值?如何解决?

        var doc = new XmlDocument();
doc.Load(@newFile);
var element = ((XmlElement)doc.GetElementsByTagName("Config/Items/Item")[0]); //null
var xmlActions = element.GetAttribute("action"); //cannot get values
var xmlFileNames= element.GetAttribute("filename"); //cannot get values

foreach (var action in xmlActions)
{
//not working
}

foreach (var file in xmlFileNames)
{
//not working
}

您的代码示例对我来说意义重大。谢谢!

最佳答案

您可以使用 LINQ to XML .以下查询返回具有 ActionFileName 属性的项目的强类型集合:

var xdoc = XDocument.Load(@newFile);

var items = from i in xdoc.Descendants("Item")
select new {
Action = (string)i.Attribute("action"),
FileName = (string)i.Attribute("fileName")
};

foreach (var item in items)
{
// use item.Action or item.FileName
}

关于C# 从 xml 属性中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18017692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com