1

I've tried this for a while, and am having trouble writing an XML start element in C# with XmlWriter.

The output line is supposed to look like: <s:Scenario xmlns:s="./scenarios" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

But the best I've been able to get has been: <s:Scenario xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:s="./scenarios" />

with the following code:

xmlWriter.WriteStartElement("s", "Scenario", "./scenarios");        
xmlWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");

Is there a better way to write this line? WriteRaw will not work, because this is supposed to be the first line following xmlWriter.WriteStartDocument();, and it ends up throwing an InvalidOperationException: "Token StartElement in state EndRootElement would result in an invalid XML document. (...)."

Let me know if you need more context! Thanks in advance.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
HelpPls
  • 11
  • 1
  • 4
    For a spec-compliant XML parser, attribute order does not matter. Why do you need that particular order of attributes? – AKX Jul 28 '20 at 18:42
  • To follow along with @AKX's comment - it doesn't really matter. You are declaring an element with two namespace attributes. What else do you need. As AKX says, attribute order doesn't matter, but the (not-spec-required) canonical order for attributes is alphabetical by name (https://en.wikipedia.org/wiki/Canonical_XML). That's what you are getting – Flydog57 Jul 28 '20 at 18:51
  • Oh! I didn't realize order didn't matter. Thanks for the tip! – HelpPls Jul 28 '20 at 19:14

0 Answers0