0

我的数据集中有 2 个表。

我需要将我的 XML 构造为:

<MyRoot>
    <Settings>
        <Param1>value1</Param1>
        <Param2>value2</Param2>
        <Param3>value3</Param3>
    </Settings>
    <Books>
      <Book>
          <BookId>1000</BookId>
          <BookName>Book1</BookName>
      </Book>
      <Book>
          <BookId>2000</BookId>
          <BookName>Book2</BookName>
      </Book>
    </Books>
</MyRoot>

但是当我使用 datSet.WriteXML(); 我得到的 XML 为:

<MyRoot>
    <Settings>
        <Param1>value1</Param1>
        <Param2>value2</Param2>
        <Param3>value3</Param3>
    </Settings>
    <Book>
       <BookId>1000</BookId>
       <BookName>Book1</BookName>
    </Book>
    <Book>
       <BookId>2000</BookId>
       <BookName>Book2</BookName>
    </Book>
</MyRoot>

因此,我无法将单独的数据集名称作为“Books”添加到第二个表(dataSet.Tables[1])。有什么办法可以做到吗?

我尝试了以下代码:

dataSet = GetList();
dataSet.DataSetName = "MyRoot"; 
dataSet.Tables[0].TableName = "Settings"; 
dataSet.Tables[1].TableName = "Books"; 
StringWriter swriter = new StringWriter(); 
dataSet.WriteXml(swriter); 
string dsResult = swriter.ToString();

谢谢。

4

2 回答 2

1

我不知道DataSet.WriteXml直接告诉以您想要的方式编写 XML 的方法,因此您有两个大选择:

  • 让我们DataSet.WriteXml编写 XML 并在之后对其进行修改。
  • 自己写序列化代码。

对于这两种方式,您有不同的选择。在第一种情况下,您可以

  • 将创建的 XML 加载到XDocumentorXmlDocument中并通过代码对其进行重组。
  • Transform your XML via XSLT (I would prefer that over the code solution)

The options in the second case should be obvious. If you create your own XmlWriter and use DataTable.WriteXml to write to it, you should be able to define your own format in a few lines of code.

To choose the right solution for your use case is up to you. I would probably go for the XSTL solution.

于 2012-10-15T08:07:42.193 回答
0

您可以通过如下代码覆盖原始 XML。

string filename = "XmlDoc.xml";
System.IO.FileStream stream = new System.IO.FileStream (filename, System.IO.FileMode.Create);
ds.WriteXml(stream); 
XmlDocument xmldoc = new XmlDocument("XmlDoc.xml");
XmlNode node1 = xmldoc.CreateNode("Books","Books");

foreach(XmlNode nd in xmldoc.Nodes) {
  if(node.value =="Book")   
    node1.AppendChild(nd);
}

xmldoc.Nodes.Add(node1);
xmldoc.SaveAs("newXmlDoc.Xml");
于 2012-10-15T07:36:43.113 回答