简体   繁体   English

将不安全的字符加载到XmlDocument中

[英]Load unsafe characters into XmlDocument

I have a computer generated string full of 'unsafe' (\\n,\\t, etc.) characters, how do I load it into a XmlDocument such as this? 我有一个完全由'unsafe'(\\ n,\\ t等)字符组成的计算机生成的字符串,如何将其加载到这样的XmlDocument中?

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>");

You should do this using the api provided for you: 您应该使用为您提供的api进行此操作:

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: 如果改为使用更新的/更好的XDocument ,则可以以更简洁的方式进行:

XNamespace a = "http://tempuri.org/";
XDocument d = XDocument.Parse(data);
d.Descendants(a + "parameter1").Single().Value = "\r\n\t&<>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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