问题
I have a computer generated string full of 'unsafe' (\n,\t, etc.) characters, how do I load it into a XmlDocument such as this?
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
<HelloWorld xmlns=""http://tempuri.org/"">
<parameter1>"+ generatedstring + @"</parameter1>
</HelloWorld>
</soap:Body>
</soap:Envelope>");
回答1:
You should do this using the api provided for you:
var data = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
<HelloWorld xmlns=""http://tempuri.org/"">
<parameter1></parameter1> <!-- we'll fill this in below -->
</HelloWorld>
</soap:Body>
</soap:Envelope>";
var xmlDoc = new XmlDocument();
var names = new XmlNamespaceManager(xmlDoc.NameTable);
names.AddNamespace("a", "http://tempuri.org/");
xmlDoc.LoadXml(data);
var containingElement = xmlDoc.SelectSingleNode("//a:HelloWorld/a:parameter1", names);
var textToAdd = "\r\n\t&<>"; //nasties
containingElement.AppendChild(xmlDoc.CreateTextNode(textToAdd)); //no problem
If you instead moved to the newer/better XDocument
, you can do it in a somewhat terser fashion:
XNamespace a = "http://tempuri.org/";
XDocument d = XDocument.Parse(data);
d.Descendants(a + "parameter1").Single().Value = "\r\n\t&<>";
来源:https://stackoverflow.com/questions/53136497/load-unsafe-characters-into-xmldocument