简体   繁体   中英

How do I replace only a specific value in an XML document without changing anything else?

I've been trying to replace a specific value from an xml document in memory before creating a message log of the XML.

I've managed to do a replace, but the Regex replace method seems to replace other items as well.

I've had to make this a little more funky than I would have liked but the elements within the document can contain different XML namespaces...

string pattern = "(<).*?(ElementName>).*?(<\\/).*?(ElementName>).*?";

string replacementPattern = "(<).*?(ReplacedElementName>)xxxxxxxxxxxxxx(<\\/).*?(ReplacedElementName>).*?";

string messageToLog = Regex.Replace(messageToSanitise, pattern, replacementPattern);

Can anyone point out where I'm going wrong?

[Update 16:11 BST 09/08/2013]

Thanks Dash, I tried to do that, but then I realised that the object Contains an xml and isn't actually an xml document itself, looks like the object has some headers, with the xml is within a document envelope. Ideally I don't want to lose any information (including the headers) before logging. There will always be 1 or 2 occurences of the element I am trying to change never more and never less than 1.

Given your xml is in the string messageToSantise , you can try the following:

Using XmlDocument:

(classic XML parsing common in older versions of the framework, and your only choice on older versions)

XmlDocument messageDoc = new XmlDocument();
messageDoc.Load(messageToSanitise);
messageDoc.SelectSingleNode(path_to_node).Value = replacementValue

path_to_node can be used with the appropriate XPath expression.

To get the xml string back out of the XmlDocument, use the messageDoc.OuterXml property.

string messageToLog = messageDoc.OuterXml;

Using XDocument:

(xml parsing via a LINQ style mechanism, supported in new versions of the framework)

XDocument messageDocument = new XDocument();
messageDocument.Parse(messageToSanitise);
messageDocument.Element(path_to_element).value = replacementValue;

To navigate through an XDocument, you may wish to also use the Descendents property. Examples of how to arrive at the node include this answer and the MSDN documentation here.

To get the Xml from the XDocument, use messageDocument.ToString();

string messageToLog = messageDocument.ToString();

This allows you to specify exactly what you want to replace.

If you want to decide whether to use XmlDocument or XDocument, I recommend reading the answer to this question .

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