希望我选择了正确的论坛。
我有一个带有一个表的数据集对象,该表来自一个通用自定义组件的GetDS方法。我需要将XML传递给另一个进程(称为字节数组)。我已经完成所有工作,但是XML缺少使用过程期望的某些属性。
我创建一个数据集对象,并可以控制TableName(根元素)的名称和像这样的行:
da.Fill(ds, "Foo")
ds.DataSetName = "FooUpload"
我使用GetXML方法序列化为如下所示的XML:
<?xml version="1.0" standalone="yes" ?>
<FooUpload>
<Foo>
<FooMasterID>483</FooMasterID>
<Country>27</Country>
<PaymentCode>ANN</PaymentCode>
<Amount>132</Amount>
<PaidDate>2012-12-31 00:00:00</PaidDate>
<PaidBy>FooServices</PaidBy>
</Foo>
</FooUpload>
调用过程期望
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<FooUpload **ClientCode="FOOO" RecordCount="1" CreateDate="2008-12-09T15:02:18.920" CreateUser="valli"**>
<Foo>
<FooMasterID>483</FooMasterID>
<Country>27</Country>
<PaymentCode>ANN</PaymentCode>
<Amount>132</Amount>
<PaidDate>2012-12-31 00:00:00</PaidDate>
<PaidBy>FooServices</PaidBy>
</Foo>
</FooUpload>
请注意FooUpload元素上的属性。此节点是数据集中的数据表的名称。
我已经搜索了如何控制XMLSerializer并找到了许多自定义对象的示例。我什至发现了将列映射设置为MappingType.Attribute的示例,该示例很接近,但我需要使用根元素来完成此操作,该元素实际上是数据集的TableName。
我感到自己很亲密,如果找不到更好的解决方案,我将不得不创建一种黑客程序,例如循环并吐出更改后的字符串以及XML的其余部分。
在此先感谢(手指交叉)!
最佳答案
您可以将GetXML的输出输入到XmlDocument中,然后添加属性。例如:
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(ds.GetXml());
XmlAttribute attr=xdoc.CreateAttribute("ClientCode");
attr.Value = "FOOOO";
xdoc.DocumentElement.Attributes.Append(attr);
然后,您可以将xdoc保存到文件中,或将其放入字符串中,例如:
XmlTextWriter xw = new XmlTextWriter(new MemoryStream(),Encoding.UTF8);
xdoc.Save(xw);
xw.BaseStream.Position = 0;
StreamReader sr = new StreamReader(xw.BaseStream);
string result = sr.ReadToEnd();
关于xml-serialization - 从数据集控制XML序列化—“TableName元素”上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1948036/