2013-03-05 80 views
3

I在XmlDocument中加载了一个XML文档。该文档由绑定到给定模式的XmlReader装载(由​​类)。获取给定XML元素的所有有效属性

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

XML看起来是这样的,并具有可选的属性:

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

列表应包含ATTRIBUTE1,attribute2,attribute3

感谢

+0

只是为了澄清,你有一些你想读的属性和其他应该忽略的属性,不是吗?无论如何,你需要[linq to xml](http://msdn.microsoft.com/en-us/library/bb387098.aspx)。 – Leri 2013-03-05 09:29:36

+1

@PLB我非常喜欢Visual Studio 2005和.NET Framework 2.0 – sblandin 2013-03-05 10:52:48

回答

3

我使用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); 
       } 
      } 
     } 

它给所有属性的列表。

+0

所以你基本上建议循环所有行元素并构建一组属性。 if子句不应该是:if(!at.LocalName.Contains(“attribute”))? – sblandin 2013-03-06 16:05:38

+1

嗨。你想要的属性包含“属性”或不?如果你没有LINQ,我能看到的唯一方法就是遍历所有的节点。 – 2013-03-06 16:13:11

相关问题