如何在写入子元素后写入顶级 XML 元素值

发布于 2024-09-12 06:02:35 字数 803 浏览 1 评论 0原文

我在这里寻求有关解决我的问题的明智建议。

我正在使用 XMLWriter 类编写 XML 文档,并以只进方式从 ADO.NET DataReader 中读取数据。在 XML 文件的顶部,我需要具有如下元素:

<datefrom>2010-07-08</datefrom>
<dateto>2010-07-10</dateto>
<total>335.00</total>

需要是数据中找到的最早日期。 是最新日期。 是文档后面列出的所有 115.00 元素的总和。

当我创建/写入 XML 元素到文件中时,我可以跟踪较早/最新的日期,并且可以不断将所有 金额加在一起以获得总计。

但是...

一旦我到达 DataReader 的末尾,您建议如何将这些值获取到 XML 文件顶部的元素中?我是否应该将替换标记作为开始和结束标记之间的值(即@datefrom、@dateto、@total)并以某种方式替换它们?这可能吗?我应该写 &关闭文件,重新打开它并将标记替换为实际值?在将 XML 写入文件之前,是否有某种方法可以用值替换标记?我没有做过太多生成 XML 文件的工作,所以我不知道是否有一些标准方法可以做到这一点。

谢谢!

I'm looking for advice here on a smart solution to my problem.

I'm writing an XML Document using the XMLWriter class and reading data out of an ADO.NET DataReader in a forward-only fashion. In the top of my XML file I need to have elements like so:

<datefrom>2010-07-08</datefrom>
<dateto>2010-07-10</dateto>
<total>335.00</total>

<datefrom> needs to be the earliest date found in the data.
<dateto> is the latest date.
<total> is the sum of all <totalpaid>115.00</totalpaid> elements listed later in the document.

As I create/write the XML elements to the file I can keep track of the earlier/latest dates and I can keep summing together all the <totalpaid> amounts to get a total.

But...

Once I've reached the end of my DataReader, how would you recommend getting those values into the elements at the top of the XML file? Should I put replacement tokens as the values between the opening and closing tags (i.e. @datefrom, @dateto, @total) and replace them somehow? Is that possible? Should I write & close the file, re-open it and replace the tokens with the actual values? Is there some way to replace the tokens with the values before writing the XML to the file? I haven't worked much with generating XML files so I don't know if there's some standard way to go about doing this.

Thanks!

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

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

发布评论

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

评论(1

丶情人眼里出诗心の 2024-09-19 06:02:35

XmlWriter 是只向前的,因此您无法插入文档开头的元素。一种可能性是对数据库执行两个 SQL 查询。第一个将聚合数据并返回您在开始时写入的三个值,然后执行第二个查询来写入其余的值。这样,聚合(最小值、最大值、总计)是在数据库级别完成的,您不需要在代码中计算它们。

如果您不能这样做,您可以使用 XDocument 允许您在任何地方插入节点,但它会将整个文档存储在内存中,如果文档很大,这可能是不可接受的。

A XmlWriter is forward-only so you cannot insert elements in the beginning of the document. One possibility is to perform two SQL queries to your database. The first one will aggregate data and return you the three values which you write in the beginning, then you perform your second query to write the rest. This way the aggregation (min, max, total) is done at the database level and you don't need to calculate them in your code.

If you can't do this you could use a XDocument which will allow you inserting nodes anywhere but it has the whole document in memory which may not be acceptable if the document is big.

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