简体   繁体   English

如何跳到 EndElement?

[英]How can I skip to an EndElement?

I have the next xml:我有下一个xml:

<work><pageSetup paperSize="9"><a foo="aa"/></pageSetup></work>

I run over the elements with:我用以下方法遍历元素:

using (XmlReader reader = XmlReader.Create(myFile.xml))
{
    while (reader.Read())
    {
        Console.WriteLine(reader.Name + " " + reader.NodeType);
        if (reader.Name == "pageSetup") reader.Skip();
    }
 }

I want to skip to the < /pageSetup> EndElement (when the "cursor" is on < pageSetup> ), but the Skip() method skips over the whole element and its EndElemet .我想跳到 </pageSetup> EndElement(当“光标”在 < pageSetup> 上时),但 Skip() 方法跳过整个元素及其 EndElemet (And this is the correct behavior of Skip() method as written inhttps://msdn.microsoft.com/en-us/library/aa720634(v=vs.71).aspx : The Skip method moves over the current element. If the node type is XmlNodeType.Element, calling Skip moves over all of the content of the element and the element end tag.) (这是在https://msdn.microsoft.com/en-us/library/aa720634(v=vs.71).aspx 中编写的 Skip() 方法的正确行为:Skip 方法在当前元素上移动.如果节点类型是 XmlNodeType.Element,则调用 Skip 会移动元素的所有内容和元素结束标记。)

What is the suitable method to use in this case?在这种情况下使用什么合适的方法?

You just keep calling Read() until Depth goes back down to the node you start with.您只需继续调用Read()直到Depth返回到您开始的节点。 Something like this should work (error handling omitted):这样的事情应该工作(省略错误处理):

int startDepth = reader.Depth; // assume you're on the start element
if (!reader.IsEmptyElement) { // if it is an <empty /> element, there is no end
    reader.Read();
    while (reader.Depth > startDepth) reader.Read();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM