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

时间:2018-11-03 23:42:59

标签: c# xml string soap

我有一个计算机生成的字符串,其中充满了“不安全”(\ 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>");

1 个答案:

答案 0 :(得分:1)

您应该使用为您提供的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

如果您改用较新/更好的XDocument,则可以以更简洁的方式进行:

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