【问题标题】:Iterate through all unknown XML attributes [duplicate]遍历所有未知的 XML 属性 [重复]
【发布时间】:2017-05-20 06:20:40
【问题描述】:

我想用 C# 遍历 XML 文件中所有给定标签的所有属性,就像在这个例子中一样。

<TAG1 Attribute1="1234" Attribute2="1234" Attribute3="1234">
      <TAG2 xpq="123" abc="000" lkj="123"/>
</TAG1>

XML 很长,标签和属性命名可以更改。 所以我必须找到一种方法来用未知的命名迭代它们。 我已经用

测试过了
XmlTextReader reader = new XmlTextReader("C:\\PathToXml\File.xml");
var optionTitle = reader.Name;                           
var AttributeName = reader.LocalName;
var AttributeValue = reader.GetAttribute(AttributeName);
var itemValue = new ListViewItem(new[] { optionTitle, AttributeName, AttributeValue });
listView1.Items.Add(itemValue);

但我只得到标签名称,没有别的......

有人对我有什么想法吗?

【问题讨论】:

标签: c# xml


【解决方案1】:

我更喜欢使用Linq2Xml

var xDoc = XDocument.Load(filename);
foreach(var attr in xDoc.Descendants("TAG1").First().Attributes())
{
    Console.WriteLine(attr.Name + " " + attr.Value);
}

【讨论】:

    【解决方案2】:

    您应该使用XDocument 来加载您的xml 文件。然后像这样使用XElement.Attributes获取所有属性

    var document = XDocument.Load("C:\\PathToXml\File.xml");
    foreach (var attribute in document.Root.Attributes)
    {
        //process the attribute
        //attribute.Name
        //attribute.Value
    }
    

    【讨论】:

      【解决方案3】:

      您应该使用XDocument 类,它提供了对 XML 文档的更简单的访问。

      var doc = XDocument.Load("C:\\PathToXml\File.xml");
      foreach(var el in doc.Descendants())
         foreach(var attr in el.Attributes())
         {
              var itemValue = new ListViewItem(new[] { el.TagName, attr.Name, attr.Value });
              listView1.Items.Add(itemValue);
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        • 1970-01-01
        • 2014-09-28
        • 1970-01-01
        • 1970-01-01
        • 2021-05-25
        相关资源
        最近更新 更多