【问题标题】:Get all valid attributes for a given XML element获取给定 XML 元素的所有有效属性
【发布时间】:2013-03-05 09:25:00
【问题描述】:

我在 XmlDocument 中加载了一个 XML 文档。该文档由绑定到给定架构的XmlReader 加载(通过XmlReaderSettings 类)。

如何获取给定文档节点元素的允许属性列表?

XML 看起来像这样并且具有可选属性:

<row attribute1="1" attribute2="2" attribute3="something">
<row attribute1="3" attribute3="something">
<row attribute2="1" attribute3="something">

列表应包含attribute1、attribute2、attribute3

谢谢

【问题讨论】:

  • 澄清一下,你有一些你想阅读的属性和其他应该被忽略的属性,不是吗?无论如何,你需要linq to xml
  • @PLB 我对 Visual Studio 2005 和 .NET Framework 2.0 印象深刻

标签: c# .net xml .net-2.0


【解决方案1】:

我用过 VS2010 但 2.0 框架。 因为您有一个架构,所以您知道属性的名称,我尝试使用您的 XML 示例创建了一个基本标记。

XML

<base>
      <row attribute1="1" attribute2="2" attribute3="something"/>
      <row attribute1="3" attribute3="something"/>
      <row attribute2="1" attribute3="something"/>
</base>

代码隐藏

        XmlDocument xml = new XmlDocument();
        xml.Load(@"C:\test.xml");

        List<string> attributes = new List<string>();

        List<XmlNode> nodes = new List<XmlNode>();
        XmlNode node = xml.FirstChild;
        foreach (XmlElement n in node.ChildNodes)
        {
            XmlAttributeCollection atributos = n.Attributes;
            foreach (XmlAttribute at in atributos)
            {
                if(at.LocalName.Contains("attribute"))
                {
                    attributes.Add(at.Value);
                }
            }
        }

它给出了一个包含所有属性的列表。

【讨论】:

  • 所以您基本上建议循环所有行元素并构建属性集合。 if 子句不应该是:if(!at.LocalName.Contains("attribute"))?
  • 嗨。您想要包含“属性”的属性吗?如果您没有 LINQ,我能看到的唯一方法是遍历所有节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 2021-08-26
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 2012-03-03
  • 2014-06-09
相关资源
最近更新 更多