【问题标题】:Output From XDocument To .CSV File in VB.NET在 VB.NET 中从 XDocument 输出到 .CSV 文件
【发布时间】:2013-08-30 18:32:52
【问题描述】:

我在将 XDocument 的输出以我希望的方式转换为 .CSV 文件时遇到了一些麻烦。我想知道是否有人可以帮助我?

首先,这是 XML:

<Main>
  <Node1>
    <Node1a>1</Node1a>
    <Node1b>2</Node1b>
  </Node1>
  <Node2>
    <Node2a>Three</Node2a>
    <Node2b>Four</Node2b>
  </Node2>
</Main>

我能够将此 XML 文档转换为字符串(即:下面称为 sString)并将其传递给我的 VB.NET 函数。我目前有...

    Dim doc As XDocument = XDocument.Parse(sString)
    Dim myOutput As New StringBuilder(1000)

    For Each node As XElement In doc.Descendants("Main")
        For Each innerNode As XElement In node.Elements()
            myOutput.AppendFormat("{0},", innerNode.Attribute("Node1a").Value)
            myOutput.AppendFormat("{0},", "!")
            myOutput.AppendFormat("{0},", innerNode.Attribute("Node1b").Value)
            myOutput.AppendFormat("{0},", "!")
            myOutput.AppendFormat("{0},", innerNode.Attribute("Node2a").Value)
            myOutput.AppendFormat("{0},", "!")
            myOutput.AppendFormat("{0},", innerNode.Attribute("Node2b").Value)
        Next

        myOutput.AppendLine()
    Next

    Dim finalCSVstring as string
    finalCSVstring = myOutput.ToString()

这“有点”有效......但我认为我在节点的内部循环上搞砸了并写出了这些值。

我想要的是最终输出的样子:

1|2|Three|Four

其中一个“|”分隔各种值。

【问题讨论】:

    标签: vb.net linq-to-xml


    【解决方案1】:

    您可以简单地在叶子元素上使用String.Join,例如

    Dim doc As XDocument = XDocument.Load("../../XMLFile1.xml")
    Dim s As String = String.Join("|", doc.Descendants().Where(Function(d) Not (d.HasElements)).Select(Function(e) e.Value))
    Console.WriteLine(s)
    

    输出1|2|Three|Four。我使用XDocument.Load 来解析输入文件中的XML,当然如果你有一个字符串使用XDocument.Parse

    在您的示例中,主要错误是使用innerNode.Attribute,因为输入示例中没有属性。所以改用innerNode.Element 就可以了。但是没有必要写循环。

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多