【问题标题】:C# get values from xml attributesC# 从 xml 属性中获取值
【发布时间】:2013-08-02 13:08:56
【问题描述】:

如何使用 C# 以正确的方式获取属性“动作”和“文件名”值?

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。它使使用 XML 变得更加容易。

标签: c# xml xmldocument


【解决方案1】:

您可以使用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
}

【讨论】:

  • var items = for i in xdoc.Descendants("Item") select new { Action = (string)i.Attribute("action"), FileName = (string)i.Attribute("fileName ") };代码语法不正确
  • @user235973457 抱歉,错字。它应该是 from 而不是 for
【解决方案2】:

GetElementsByTagName找到你的直系后代。该参数应该是只是一个标签名称,而不是整个元素路径。

如果您想在提供 XPath 表达式的同时搜索整个文档,请改用 SelectNodes

对于您的文档,它应该如下所示:

var element = (XmlElement)doc.SelectNodes("/Config/Items/Item")[0];

【讨论】:

  • 我试过 SelectNode 但不知道如何在代码中使用它。你能给我示例代码吗?
  • @user235973457:我添加了示例调用;我现在不能尝试,但我希望命名空间不会有问题。如果您遇到任何错误,请提供确切的错误消息,我或附近的任何人稍后会尝试。
  • @user235973457:你的意思是XmlActions 只包含一个元素?这是意料之中的,因为GetAttribute 将只返回一个属性节点。如果你真的想得到“action 属性为...的所有节点”,迭代来自SelectNodes&lt;Item&gt; 元素的集合)的结果并从 每个其中一个&lt;Item&gt;元素。
【解决方案3】:

您可以通过LINQ to XML 实现您的要求:

// For each element that is a child of your Items element that is named Item
foreach (var item in XElement.Load("file.xml").Descendants("Items").Elements("Item"))
{
    // If the element does not have any attributes
    if (!item.Attributes().Any())
    {
        // Lets skip it
        continue;
    }

    // Obtain the value of your action attribute - Possible null reference exception here that should be handled
    var action = item.Attribute("action").Value;
    // Obtain the value of your filename attribute - Possible null reference exception here that should be handled
    var filename = item.Attribute("filename").Value;

    // Do something with your data
    Console.WriteLine("action: {0}, filename {1}", action, filename);
}

【讨论】:

    【解决方案4】:

    问题中的代码有一堆问题:
    1. 您在 GetElementsByTagName 中使用 XPath,只需使用标记
    2. 您只能使用 [0]
    获取 XmlNodeCollection 中的第一个 XmlNode 3. 由于您只有一个 XmlNode,因此您只会获得用于获取属性的字符串结果,而不是字符串集合,然后您将尝试通过它进行枚举
    4.你的foreach坏了,结果对象没有类型

    这是一个可以工作的 sn-p:

    var doc = new XmlDocument();
    doc.Load("test.xml");
    var items = doc.GetElementsByTagName("Item");
    
    var xmlActions = new string[items.Count];
    var xmlFileNames = new string[items.Count];
    for (int i = 0; i < items.Count; i++) {
        var xmlAttributeCollection = items[i].Attributes;
        if (xmlAttributeCollection != null) {
            var action = xmlAttributeCollection["action"];
            xmlActions[i] = action.Value;
    
            var fileName = xmlAttributeCollection["filename"];
            xmlFileNames[i] = fileName.Value;
        }
    }
    
    foreach (var action in xmlActions) {
        //working
    }
    
    foreach (var file in xmlFileNames) {
        //working
    }
    

    或者,如果您在对集合中的所有操作和文件名进行操作之前不需要它们,您可以只对 for 循环中的每个操作/文件名进行操作。

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2020-06-16
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 2020-08-18
      相关资源
      最近更新 更多