我正在嘗試使用 dataset readxml 方法從 xml 檔案創建資料表。但是我正在努力正確定義架構以正確解釋此檔案。
我認為問題在于嵌套以及 ColumnUid (理想情況下應該是列名)是一個值而不是一個元素的事實。
它目前回傳的資料表具有以下結構:[
我希望讓它像這樣回傳:
這是否可以通過定義正確的模式傳遞給 readxml 來實作......甚至根本沒有?
我可能會在初始 readxml 之后轉置資料表,使用 linq 或回圈,但更愿意避免這種情況
xml如下(縮短示例):
<?xml version="1.0" encoding="utf-16"?>
<DataTable Uid="dtDocRows">
<Rows>
<Row>
<Cells>
<Cell>
<ColumnUid>DocEntry</ColumnUid>
<Value>121496</Value>
</Cell>
<Cell>
<ColumnUid>DocNum</ColumnUid>
<Value>264803</Value>
</Cell>
<Cell>
<ColumnUid>LineNum</ColumnUid>
<Value>0</Value>
</Cell>
<Cell>
<ColumnUid>ItemCode</ColumnUid>
<Value>BENIGRAMST55060075L</Value>
</Cell>
<Cell>
<ColumnUid>Quantity</ColumnUid>
<Value>1.000000</Value>
</Cell>
</Cells>
</Row>
<Row>
<Cells>
<Cell>
<ColumnUid>DocEntry</ColumnUid>
<Value>121658</Value>
</Cell>
<Cell>
<ColumnUid>DocNum</ColumnUid>
<Value>264965</Value>
</Cell>
<Cell>
<ColumnUid>LineNum</ColumnUid>
<Value>0</Value>
</Cell>
<Cell>
<ColumnUid>ItemCode</ColumnUid>
<Value>PYCCHANT202575L</Value>
</Cell>
<Cell>
<ColumnUid>Quantity</ColumnUid>
<Value>1.000000</Value>
</Cell>
</Cells>
</Row>
回傳資料表的c#函式是這樣的:
private DataTable getDotNetDataTable()
{
DataSet ds = new DataSet();
XDocument xdoc = XDocument.Parse(dtDocRows.SerializeAsXML(SAPbouiCOM.BoDataTableXmlSelect.dxs_DataOnly));
xdoc.Save(@"C:\1\xml\test.xml");
ds.ReadXml(@"C:\1\xml\test.xml");
return ds.Tables.Item(4);
return dt;
}
uj5u.com熱心網友回復:
使用 XML 行:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.IO;
namespace ConsoleApplication23
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
//remove utc-16
StreamReader reader = new StreamReader(FILENAME);
reader.ReadLine();
XDocument doc = XDocument.Load(reader);
string[] columnNames = doc.Descendants("ColumnUid").Select(x => (string)x).Distinct().ToArray();
DataTable dt = new DataTable();
foreach (string columnName in columnNames)
{
dt.Columns.Add(columnName, typeof(string));
}
foreach (XElement xRow in doc.Descendants("Row"))
{
DataRow dtRow = dt.Rows.Add();
foreach(XElement cell in xRow.Descendants("Cell"))
{
string colName = (string)cell.Element("ColumnUid");
string value = (string)cell.Element("Value");
dtRow[colName] = value;
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/495845.html
