2013-08-30 31 views
0

我從XDocument獲得輸出的方式有點麻煩,我希望它成爲一個.CSV文件。我想知道有人能幫助我嗎?從XDocument輸出到VB.NET中的.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 

,其中「|」分離各種值。

回答

0

您可以簡單地在葉元素上使用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可以。但是不需要編寫循環。