Search code examples
c#xmlskip

C# Skip anything to next tag


I have a log file in xml format like

<log> // skip this node
  <?xml version="1.0" encoding="UTF-8"?>
  <qbean logger="main-logger">
  </qbean>
</log>
<log> // go to this node
</log>

Now ReadToNextSibling("log") throw an exception an I need to skip content of first "log" tag and move to next "log" tag without throwing exception. Is there a way?


Solution

  • Hint:

    1. Your XML is invalid since the <?xml version="1.0" encoding="UTF-8"?> has to be before the root element. You can search for it and remove it if that fixes your problem. You can use yourXml.Repalce("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "")
    2. You have to create a root element for your XML to be valid for parsing.

    Then, you can use the XmlDocument class to parse the XML data that you have and skip anything you want. You would need something like this:

    var document = new XmlDocument();
    
    document.LoadXml(yourXml);
    
    document.DocumentElement.ChildNodes[1]