XmlWriter 写入字符串而不是文件 [英] XmlWriter to Write to a String Instead of to a File

查看:21
本文介绍了XmlWriter 写入字符串而不是文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要返回 XML 字符串的 WCF 服务.但似乎作者只想建立一个文件,而不是一个字符串.我试过了:

I have a WCF service that needs to return a string of XML. But it seems like the writer only wants to build up a file, not a string. I tried:

string nextXMLstring = "";
using (XmlWriter writer = XmlWriter.Create(nextXMLstring))

这会产生一个错误,指出 nextXMLstring 没有文件路径.它想要类似的东西:

This generates an error saying nextXMLstring doesnt have a file path. It wants something like:

using (XmlWriter writer = XmlWriter.Create("nextXMLstring.xml"))

如何构建我的 XML,然后将其作为字符串返回??

How can I build up my XML and then return it as a string??

谢谢!!

推荐答案

您需要创建一个 StringWriter,并将其传递给 XmlWriter.

You need to create a StringWriter, and pass that to the XmlWriter.

XmlWriter.Create 的字符串重载用于文件名.

The string overload of the XmlWriter.Create is for a filename.

例如

using (var sw = new StringWriter()) {
  using (var xw = XmlWriter.Create(sw)) {
    // Build Xml with xw.


  }
  return sw.ToString();
}

这篇关于XmlWriter 写入字符串而不是文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆