【问题标题】:Checking XML values in a List检查列表中的 XML 值
【发布时间】:2020-08-07 13:02:01
【问题描述】:

我有一个包含数字的字符串列表,如下所示 {"2","5","7"}

我也有一个像下面这样的 xml

<Product>
   <Record>
      <Categories>
        <SubCategories>  
           <References>2</References>
           <References>1</References>
           <References>10</References>
        </SubCategories>
      </Categories>
      <Categories>
        <SubCategories>  
           <References>154</References>
            <References>75</References>
           <References>0</References>
        </SubCategories>
      </Categories>
      <Categories>
        <SubCategories>  
           <References>7</References>
        </SubCategories>
      </Categories>          
   </Record>
</product>

我想检索一个单独的 xml 文件中的所有类别,其引用值至少包含上述列表中存在的值之一

我不知道如何继续

xmldoc.load(filepath) (xmldoc is the xmldocument of the file)
Dim CategoriesList = xmldoc.descendants("Record")
for each item in CategoriesList 
   Dim SubCategoriesList = item.descendants("Subcategories")
Next

请告诉我如何检查这些值并获取所需的类别

【问题讨论】:

    标签: xml vb.net xslt xml-parsing xmldocument


    【解决方案1】:

    您可以使用AnyHashSet(Of String) 来检查“类别”元素是否具有带有其中一个值的“参考”

    Dim required = New String() {"1", "2", "3"}.ToHashSet()
    Dim product = XDocument.Load("path-to-file")
    
    Dim categories = product.Descendants("Categories").
        Where(Function(category) category.
            Descendants("References").
            Any(Function(r) required.Contains(r.Value))
        ).
        ToArray()
    

    HashSet 是为了减少枚举值的数量,HashSet.Contains 只需要一个操作 O(1) 来检查值。

    【讨论】:

    • 感谢您的回答。但是类别指的是什么。当我使用 ToHashSet 时,第一行也会出错。它似乎不是 String() 的成员
    • 导入System.Linq?
    • 类别为XElement
    • 您是否将 vb.net 与 C# 混合在一起,因为我得到了红色曲线。在 vb.net 中无法识别 =>。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多