CorribView CorribView - 8 months ago 98
C# Question

Modifying element of Json string (in C#)

I'm trying to modify an attribute of an XML string using Json in C#. Currently I'm doing the following:

XmlDocument serializedFormXml = new XmlDocument();

string formJsonString = JsonConvert.SerializeXmlNode(serializedFormXml, Newtonsoft.Json.Formatting.None, true);
JObject formJsonObj = JObject.Parse(formJsonString);
formJsonObj["@code"] = "myNewValue";
var xml = JsonConvert.DeserializeXmlNode(formJsonObj.ToString()).ToString();

When I do this I get get an exception on the last line:
Unable to cast object of type 'Newtonsoft.Json.Converters.XmlDocumentWrapper' to type 'Newtonsoft.Json.Converters.IXmlElement'

Any ideas what I'm doing wrong and how I can fix modify my form attribute "code"?

This is the XML I'm using:

<Form code="XYZ">


dbc dbc

That's going to be way, way easier with Linq-to-XML:

        var doc = XDocument.Parse(mySerializedForm);
        doc.Root.SetAttributeValue(doc.Root.Name.Namespace + "code", "myNewValue");
        var xml = doc.ToString();

This drops the XML declaration. If you need the XML declaration included, you can use the following extension method:

public static class XObjectExtensions
    public static string ToXml(this XDocument xDoc)
        using (var writer = new StringWriter())
            return writer.ToString();

And then write:

        var xml = doc.ToXml();

If specifically you need to make the encoding string say "UTF-8", use Utf8StringWriter from this answer.


The reason you code fails is that you stripped the XML root element name away when you converted to json by passing true here:

        string formJsonString = JsonConvert.SerializeXmlNode(serializedFormXml, Newtonsoft.Json.Formatting.None, true);

Thus you need to add it back when converting back:

        var xml = JsonConvert.DeserializeXmlNode(formJsonObj.ToString(), serializedFormXml.DocumentElement.Name).ToString();