从 C# 中的 XML 编写器创建 XML 元素对象

发布于 2024-07-14 07:56:15 字数 139 浏览 4 评论 0原文

我正在用 C# 编写 Windows 服务。 我有一个 XmlWriter,它包含 XSLT 转换的输出。 我需要将 XML 放入 XMLElement 对象中以传递给 Web 服务。

做这个的最好方式是什么?

I'm writing a Windows service in C#. I've got an XmlWriter which is contains the output of an XSLT transformation. I need to get the XML into an XMLElement object to pass to a web service.

What is the best way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

分開簡單 2024-07-21 07:56:15

您不需要中间字符串,可以创建一个直接写入 XmlNode 的 XmlWriter:

XmlDocument doc = new XmlDocument();
using (XmlWriter xw = doc.CreateNavigator().AppendChild()) {
  // Write to `xw` here.
  // Nodes written to `xw` will not appear in the document 
  // until `xw` is closed/disposed.
}

并将 xw 作为转换的输出传递。

注意。 xsl:output 的某些部分将被忽略(例如编码),因为 XmlDocument 将使用其自己的设置。

You do not need an intermediate string, you can create an XmlWriter that writes directly into an XmlNode:

XmlDocument doc = new XmlDocument();
using (XmlWriter xw = doc.CreateNavigator().AppendChild()) {
  // Write to `xw` here.
  // Nodes written to `xw` will not appear in the document 
  // until `xw` is closed/disposed.
}

and pass xw as the output of the transform.

NB. Some parts of the xsl:output will be ignored (e.g. encoding) because the XmlDocument will use its own settings.

人心善变 2024-07-21 07:56:15

嗯,XmlWriter包含输出; 通常,您有一个作为转储位置的支持对象(可能是 StringBuilder 或 MemoryStream)。 在这种情况下,StringBuilder 可能是最有效的......也许类似于:

    StringBuilder sb = new StringBuilder();
    using (XmlWriter writer = XmlWriter.Create(sb))
    {
        // TODO write to writer via xslt
    }
    string xml = sb.ToString();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    XmlElement el = doc.DocumentElement;

Well, an XmlWriter doesn't contain the output; typically, you have a backing object (maybe a StringBuilder or MemoryStream) that is the dumping place. In this case, StringBuilder is probably the most efficient... perhaps something like:

    StringBuilder sb = new StringBuilder();
    using (XmlWriter writer = XmlWriter.Create(sb))
    {
        // TODO write to writer via xslt
    }
    string xml = sb.ToString();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    XmlElement el = doc.DocumentElement;
潜移默化 2024-07-21 07:56:15

如果您提供一个编写器,您就提供了一个存储库,其中输出生成器正在传输数据,因此 Richard 的重播效果很好,您实际上不需要字符串生成器将数据从读取器发送到 XmlDocument!

If you provide a writer, you provide a repository where an output generator is transferring data, thus the replay of Richard is good, you don't really need a string builder to send data from a reader to an XmlDocument!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文