Load unsafe characters into XmlDocument

[亡魂溺海] 提交于 2019-12-25 00:34:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!