如何检查元素的名称与WriteEndElement元素、名称、WriteEndElement

由网友(旧年素颜、君记否)分享简介:我在写XML与的XmlWriter 。我的code有很多部分是这样的:I'm writing xml with XmlWriter. My code has lots of sections like this:xml.WriteStartElement("payload");ThirdPartyLibrary....

我在写XML与的XmlWriter 。我的code有很多部分是这样的:

I'm writing xml with XmlWriter. My code has lots of sections like this:

xml.WriteStartElement("payload");
ThirdPartyLibrary.Serialise(results, xml);
xml.WriteEndElement(); // </payload>

的问题是, ThirdPartyLibrary.Serialise 方法是不可靠的。它可以发生(取决于具体的变量结果),它并没有关闭所有它打开的标签。因此,我WriteEndElement线是变态的,消耗闭库的挂标签,而不是写&LT; /有效载荷GT;

The problem is that the ThirdPartyLibrary.Serialise method is unreliable. It can happen (depending on the variable results) that it doesn't close all the tags it opens. As a consequence, my WriteEndElement line is perverted, consumed closing the library's hanging tags, rather than writing </payload>.

因此​​,我想提出来WriteEndElement,检查该元素的名称,并抛出一个异常,除非光标是在预期元素检查通话。

Thus I'd like to make a checked call to WriteEndElement that checks the element name, and throws an exception unless the cursor is at the expected element.

xml.WriteEndElement("payload");

您可以把它像 XmlReader.ReadStartElement(名称)会抛出,除非光标在文件中预期的地方。

You can think of this like XmlReader.ReadStartElement(name) which throws unless the cursor is at the expected place in the document.

我怎样才能做到这一点?

How can I achieve this?

编辑:第二个用例此扩展方法是使自己的code更具可读性和可靠性

A second use case for this extension method would be to make my own code more readable and reliable.

推荐答案

在最后,我写了一个延伸的方法 WriteSubtree ,给出了可用的API:

In the end, I wrote an extention method WriteSubtree that gives this usable API:

using (var resultsXml = xml.WriteSubtree("Results"))
{
    ThirdPartyLibrary.Serialise(results, resultsXml);
}

扩展方法 XmlWriter.WriteSubtree 类似于.NET的 XmlReader.ReadSubtree 。它返回一个特殊的XmlWriter,检查对滑稽的生意。它的处置方法将关闭所有还在打开的标签。

The extension method XmlWriter.WriteSubtree is analogous to .NET's XmlReader.ReadSubtree. It returns a special XmlWriter that checks against funny business. Its dispose method closes any tags left open.

阅读全文

相关推荐

最新文章