简体   繁体   中英

C# XMLDocument Encoding?

I'm trying to code a function that validates an XML settings file, so if a node does not exist on the file, it should create it.

I have this function

private void addMissingSettings() {
    XmlDocument xmldocSettings = new XmlDocument();
    xmldocSettings.Load("settings.xml");

    XmlNode xmlMainNode = xmldocSettings.SelectSingleNode("settings");

    XmlNode xmlChildNode = xmldocSettings.CreateElement("ExampleNode");
    xmlChildNode.InnerText = "Hello World!";

    //add to parent node
    xmlMainNode.AppendChild(xmlChildNode);
    xmldocSettings.Save("settings.xml");
}

But on my XML file, if I have

<rPortSuffix desc="Read Suffix">&#13;&#10;</rPortSuffix>
<wPortSuffix desc="Write Suffix">&#03;</wPortSuffix>

When the I save the document, it saves those lines as

<rPortSuffix desc="Read Suffix">
</rPortSuffix>
<wPortSuffix desc="Sufijo en puerto de escritura">&#x3;</wPortSuffix>
<ExampleNode>Hello World!</ExampleNode>

Is there a way to prevent this behaviour? Like setting a working charset or something like that?

The two files are equivalent, and should be treated as being equivalent by all XML parsers, I believe.

Additionally, Unicode character U+0003 isn't a valid XML character , so you've fundamentally got other problems if you're trying to represent it in your file. Even though that particular .NET XML parser doesn't seem to object, other parsers may well do so.

If you need to represent absolutely arbitrary characters in your XML, I suggest you do so in some other form - eg

<rPortSuffix desc="Read Suffix">\u000c\u000a</rPortSuffix>
<wPortSuffix desc="Write Suffix">\u0003</wPortSuffix>

Obviously you'll then need to parse that text appropriately, but at least the XML parser won't get in the way, and you'll be able to represent any UTF-16 code unit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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