/// <summary> /// Reads the json data and creates a custom XML part with the same parameters. /// /// If a custom XML part with the same namespace exists it is replaced with the new data /// and if it doesn't it is added. /// </summary> /// <param name="doc">The document that will receive the custom XML part</param> /// <param name="jsonData">The data that will get added in the custom XML part. Must be a valid JSON string with one ore more root elements</param> /// <param name="xmlNamespace">The namespace that will identify the newly created CustomXmlPart. It is also used to determine if it already exists</param> /// <returns>The replaced or newly created CustomXmlPart</returns> public static CustomXmlPart AddOrReplaceCustomXmlPart(this WordprocessingDocument doc, string jsonData, string xmlNamespace) { if (string.IsNullOrWhiteSpace(xmlNamespace)) { throw new XmlNamespaceNotFoundException("Xml namespace not provided"); } XDocument xDoc; try { xDoc = JsonConvert.DeserializeXNode(jsonData); } catch (JsonSerializationException) { //For the xdoc to be valid it needs to have a single root element, transform the json so it matches the requirement xDoc = JsonConvert.DeserializeXNode("{\"root\": " + jsonData + "}"); } XNamespace myNs = xmlNamespace; //Assign the namespace to the elements foreach (var el in xDoc.Descendants()) { el.Name = myNs + el.Name.LocalName; } return(doc.AddOrReplaceCustomXmlPart(xDoc)); }