简体   繁体   English

如何使用xmlreader读取此xml

[英]How to use xmlreader to read this xml

My xml section is like this: 我的xml部分是这样的:

<Note>
<SpecialText att1="" />
</Note>

Or 要么

<Note>
This is a note.
</Note>

What I need is to use XmlReader to read the xml, but I am not sure how to determine if the innerXml is another xmlelement or is just text. 我需要使用XmlReader来读取xml,但是我不确定如何确定innerXml是另一个xmlelement还是仅仅是文本。

I am doing this: 我正在这样做:

while (reader.Read())
{
    if (reader.NodeType == XmlNodeType.Element)
    {
        switch (reader.LocalName.ToLower())
        {
            case MMLElement.SpecialText:
            //// read related attributes
            break;
        }
   }
}

but how can I read the content if the thing under the Note is just text. 但是如果“注释”下的内容仅仅是文本,我该如何阅读内容。 If I use reader.ReadInnerXml, it will read everything, so I won't have chance to see if it is a SpecialText XmlElement or just text? 如果使用reader.ReadInnerXml,它将读取所有内容,因此我将没有机会查看它是SpecialText XmlElement还是仅文本?

Many Thanks 非常感谢

If you use XElement.Load(file) , you can then use... 如果使用XElement.Load(file) ,则可以使用...

XElement xfile = XElement.Load(file);
XElement note = xfile.Path("path/to/note");
if(note.HasElements) 
    // read the element
else 
    string text = (string)note;

Note: Get Path() here: https://github.com/ChuckSavage/XmlLib/blob/master/XElementExtensions.cs 注意:在此处获取Path(): https : //github.com/ChuckSavage/XmlLib/blob/master/XElementExtensions.cs

Now this may sound condescending, but I think that this is something easily answered by digging in the reference. 现在,这听起来固然居高临下,但是我认为,通过深入研究参考资料可以轻松地回答这一点。 Then again I may not fully understand your problem. 再说一次,我可能无法完全理解您的问题。 If the following answer is not what you are looking for, just post more details and I'll be glad to help. 如果以下答案不是您想要的,请发表更多详细信息,我们将很乐意为您提供帮助。

To determine if the content is just text, just check for it and then do with it whatever you like: 要确定内容是否仅为文本,只需对其进行检查,然后根据需要对其进行处理:

while (reader.Read())             
    {             
    if (reader.NodeType == XmlNodeType.Element)             
    {             
        switch (reader.LocalName.ToLower())             
        {             
            case MMLElement.SpecialText:             
            //// read related attributes             
            break;             
        }             
    }             

    else if (reader.NodeType == XmlNodeType.Text) 
    { 
      string thisIsjustText = reader.value;
    }
    //whatever comes next
}

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

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