简体   繁体   English

在给定元素时检索 XML“id”属性值

[英]Retrieve the XML “id” attribute value when given an element

Thank you for reading this.谢谢您阅读此篇。 I need to get the names of the <table> elements in an XML document and use those names to poulate a combo box on a winform.我需要获取 XML 文档中<table>元素的名称,并使用这些名称在 winform 上填充组合框。 I am trying to create a method in c# to retrieve the value of an 'id' attribute based on the xml structure:我正在尝试在 c# 中创建一个方法来检索基于 xml 结构的“id”属性的值:

<root>
     <object>
          <objects>
               <table id="tableName">
               </table>
          </objects>
     </object>
</root>

I have looked on the Microsoft docs site and have found several things talking about getelementbytagname or getelementbyid.我查看了 Microsoft 文档站点,发现了一些关于 getelementbytagname 或 getelementbyid 的内容。 Those are close but they are not getting me the information I need.这些很接近,但他们没有让我得到我需要的信息。 I also tried pathing to them in a method using xpath in order to retrieve the data but I cannot get it to work.我还尝试在使用 xpath 的方法中路径到它们以检索数据,但我无法让它工作。 This is probably super elementary but I have searched online for two days now and can't figure it out.这可能是超级初级,但我已经在网上搜索了两天,无法弄清楚。 Any help would be greatly appreciated.任何帮助将不胜感激。

You could Parse (or Load, in case it is an .xml file) it using Linq To XML and get what you want.您可以使用 Linq To XML 解析(或加载,如果它是 .xml 文件)它并获得您想要的。 With this very few data there is no identification but this would get you started:有了这很少的数据,就没有身份证明,但这会让你开始:

void Main()
{
    string myXML = @"<root>
     <object>
          <objects>
               <table id=""tableName"">
               </table>
          </objects>
     </object>
</root>";

    var ids = XElement.Parse(myXML).DescendantsAndSelf("table")
              .Where(xe => xe.Attribute("id") != null)
              .Select(xe => (string)xe.Attribute("id"));
              
    foreach (var id in ids)
    {
        Console.WriteLine(id);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM