[英]How will I convert value in StringWriter into XML Format.?
I have written a Service and in the I need a return type as n XML which I will passing to Client. 我已经编写了一个Service,在其中,我需要将返回类型作为n XML传递给Client。 I am having Values in string writer as -
<newdataset> <table> <Slno>1</Slno></table><Name>Andrew</Name><table><Slno>2</Slno><name>Trisha</name></table></newdataset>
我在字符串
<newdataset> <table> <Slno>1</Slno></table><Name>Andrew</Name><table><Slno>2</Slno><name>Trisha</name></table></newdataset>
具有以下值- <newdataset> <table> <Slno>1</Slno></table><Name>Andrew</Name><table><Slno>2</Slno><name>Trisha</name></table></newdataset>
What I need to return is a proper XML format from the service to the client. 我需要返回的是从服务到客户端的正确XML格式。
PS - It should have a header like all the XMLs has -- like this : < ?xml version="1.0" standalone="yes"?>
PS-应该像所有XML一样具有标题-像这样:<
?xml version="1.0" standalone="yes"?>
Thanks, 谢谢,
Nayan 拿烟
Use the DataTable.WriteXml(XmlWriter)
overload. 使用
DataTable.WriteXml(XmlWriter)
重载。 Then when creating the XmlWriter
you can pass in an XmlWriterSettings
with the necessary formatting options, including setting settings.OmitXmlDeclaration = false
(which is actually the default). 然后,在创建
XmlWriter
您可以传入XmlWriterSettings
,其中包含必要的格式选项,包括设置settings.OmitXmlDeclaration = false
(这实际上是默认值)。 Thus: 从而:
public static string ToXml(this DataTable dt)
{
using (var textWriter = new StringWriter())
{
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
// settings.OmitXmlDeclaration = false; not necessary since this is the default anyway.
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
{
dt.WriteXml(xmlWriter);
return textWriter.ToString();
}
}
}
Thus gives the output: 从而给出输出:
<?xml version="1.0" encoding="utf-16"?>
<newdataset>
<Name>Andrew</Name>
<table>
<Slno>1</Slno>
</table>
<table>
<Slno>2</Slno>
<name>Trisha</name>
</table>
</newdataset>
The same will work for a DataSet
as well if you have one. 如果您有一个,同样适用于
DataSet
。 (For reasons unclear to me, the WriteXml(TextWriter)
overload omits the XML declaration.) (由于我不清楚的原因,
WriteXml(TextWriter)
重载省略了XML声明。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.