【问题标题】:Select one value from XML Document从 XML 文档中选择一个值
【发布时间】:2020-06-01 19:47:39
【问题描述】:

我只想要一个使用 VB 的 XML 文件中的值。 XML文件是这样的

<?xml version="1.0" encoding="utf-8"?>
<Books>
    <Book ID="12345">
        <Name>One Flew Over The Cuckoo's Nest</Name>
        <ISBN>Some cataloging ID</ISBN>
        <Author>Ken Kesey</Author>
        <More>Something here</More>
    </Book>
</Books>

在此示例中,我只想获取作者为“Ken Kesey”的图书的 ISBN 号。我试过这个;

        Dim xl As XElement = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + "\Books.xml")
        Dim Auth As String = From elem In xl.Elements("Books").Elements("Book")
                             Where elem.Element("ISBN").Value = "Some cataloging ID"
                             Select elem.Element("Author").Value

还有许多相同的变体,但没有效果。

感谢您的关注。

【问题讨论】:

    标签: xml vb.net linq


    【解决方案1】:

    这里是如何查询 XML 并根据 Author 元素查找一本书的 ISBN

    我使用.Parse() 方法是因为我不想创建文件。

    VB.NET

    Sub Main
        Dim xelem As XElement = XElement.Parse("<Books>
        <Book ID='12345'>
            <Name>One Flew Over The Cuckoo's Nest</Name>
            <ISBN>Some cataloging ID</ISBN>
            <Author>Ken Kesey</Author>
            <More>Something here</More>
        </Book>
    </Books>")
    
        Dim ISBN As String = xelem.Elements("Book") _
            .Where(Function(x) x.Element("Author").Value.Equals("Ken Kesey")) _ 
            .[Select](Function(x) CStr(x.Element("ISBN").Value)).FirstOrDefault()
    
        Console.WriteLine(ISBN)
    End Sub
    

    【讨论】:

      【解决方案2】:

      更简洁的形式(利用 VB.NET XML Literals):

      Dim books =
          <?xml version="1.0" encoding="utf-8"?>
          <Books>
              <Book ID="12345">
                  <Name>One Flew Over The Cuckoo's Nest</Name>
                  <ISBN>Some cataloging ID</ISBN>
                  <Author>Ken Kesey</Author>
                  <More>Something here</More>
              </Book>
          </Books>
      Dim isbn = books.<Books>.<Book>.Where(Function(b) b.<Author>.Value = "Ken Kesey").<ISBN>.Value
      

      【讨论】:

      • 感谢您的回复。您的解决方案将无法构建。在我的示例中,xl 是 XElement,因此我的 isbn= 将以 xl.. 开头,这会导致错误提示“Leading”。要么 ”!”只能出现在“With”语句中。它以一种奇怪的方式将所有内容隔开。
      • 为什么不建?这对我有用。如果您使用 XDocument,那么它会起作用。
      猜你喜欢
      • 2012-04-10
      • 2020-04-01
      • 1970-01-01
      • 2023-03-22
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多