C# XMLDocument 到 DataTable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/836806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:34:38  来源:igfitidea点击:

C# XMLDocument to DataTable?

c#.netdatatabledatasetxmldocument

提问by Matt Dell

I assume I have to do this via a DataSet, but it doesn't like my syntax.

我假设我必须通过 DataSet 来做到这一点,但它不喜欢我的语法。

I have an XMLDocument called "XmlDocument xmlAPDP".

我有一个名为“XmlDocument xmlAPDP”的 XMLDocument。

I want it in a DataTable called "DataTable dtAPDP".

我希望它在名为“DataTable dtAPDP”的数据表中。

I also have a DataSet called "DataSet dsAPDP".

我还有一个名为“DataSet dsAPDP”的数据集。

-

——

if I do DataSet dsAPDP.ReadXML(xmlAPDP) it doesn't like that because ReadXML wants a string, I assume a filename?

如果我做 DataSet dsAPDP.ReadXML(xmlAPDP) 它不喜欢因为 ReadXML 想要一个字符串,我假设一个文件名?

采纳答案by Matthew Flaschen

No hacks required:

不需要黑客:

xmlAPDP = new XmlDocument()
...
xmlReader = new XmlNodeReader(xmlAPDP)
dataSet = new DataSet()
...
dataSet.ReadXml(xmlReader)

XmlDocument is an XmlNode, and XmlNodeReader is a XmlReader, which ReadXml accepts.

XmlDocument 是一个 XmlNode,而 XmlNodeReader 是一个 XmlReader,ReadXml 接受它。

回答by Kon

How about something like this?

这样的事情怎么样?

dsAPDP.ReadXml(new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xmlAPDP.OuterXml)))

回答by Bob Yenser

ASP.net example:

ASP.net 示例:

private DataTable GetReportDataTable()
{
    //get mapped path to xml document
    string xmlDocString = Server.MapPath("CustomReports.xml");

    //read into dataset
    DataSet dataSet = new DataSet();
    dataSet.ReadXml(xmlDocString);

    //return single table inside of dataset
    return dataSet.Tables[0];
}