-1

I have this method

public object ReturnXML()
        {
            var path = @"C:\path\Stuff.xml";
            //Option A
            var contents = XElement.Load(path);
            //Option B
            var contents = File.ReadAllText(path);

            return contents;
        }

Option A works just fine, except when XML file is structurally wrong. I want XML to be returned even when it is structurally wrong. Option B works, but that is string. Is it possible to return structurally incorrect XML as XML?

Eric Klaus
  • 923
  • 1
  • 9
  • 24
  • No, most XML parsers won't allow you to parse invalid XML. I don't know of one in the standard library that does. – Jon Skeet Nov 15 '19 at 17:27
  • If we can't return XML, do you have any suggestions to use instead of string (Option B)? Using string for that purposes seems really odd to me – Eric Klaus Nov 15 '19 at 17:29
  • 1
    Really odd for *what* purposes? You haven't explained what you want to do, or what the input looks like. A parser could handle *some* problems by discarding invalid elements but not all. If one closing tag and the *next* opening tag are missing, how will the parser decide what to discard? – Panagiotis Kanavos Nov 15 '19 at 17:31
  • You can use XmlReader instead of a DOM-like parser to read elements as they appear in the file and decide what to do with errors. You may decide for example to skip elements until you find the next valid element of type X. If for example the file contains orders and order items and you get an error inside an order item, you could skip to the next *order* – Panagiotis Kanavos Nov 15 '19 at 17:31
  • *How* is this XML invalid? –  Nov 15 '19 at 17:33
  • 3
    @EricKlaus Malformed XML *is not* XML. If it's not XML, then what is it, if not a string? – StackOverthrow Nov 15 '19 at 17:37
  • Everything what you say makes sense. Thank you all. I'll just stick with string version instead – Eric Klaus Nov 15 '19 at 18:41
  • 1
    Does this answer your question? [How to parse invalid (bad / not well-formed) XML?](https://stackoverflow.com/questions/44765194/how-to-parse-invalid-bad-not-well-formed-xml) – Progman Nov 15 '19 at 20:31

1 Answers1

0

It is not possible, because you are trying to create an element from a wrong code. It is like a syntax error in C#, code will not compile.

Emanuele
  • 723
  • 4
  • 15