read xml document and update all fields c# - c#

i'm trying to read xml file and update all it's value my xml was
<adf>
<prospect>
<requestdate>2015-10-29 07-38-22</requestdate>
<id sequence="1" source="admin.ss.com">admin.ss.com</id>
<vehicle interest="buy" status="">
<id sequence="1" source=""></id>
<year></year>
<make></make>
<model>camry</model>
<vin></vin>
<stock></stock>
<trim></trim>
</vehicle>
<customer>
<contact primarycontact="1">
<name part="first">Jessica</name>
<name part="last">Sonntag</name>
<email>js#test.com</email>
<phone type="phone" time="day">555-585-5555</phone>
<address>
<street line="1"></street>
<city></city>
<regioncode></regioncode>
<postalcode></postalcode>
<country></country>
</address>
</contact>
<comments>Vehicle Year: 2011 Comments: </comments>
</customer>
<provider>
<name part="full">ST</name>
<service> Engine Marketing</service>
<phone>1-866-572-3952</phone>
</provider>
</prospect>
</adf>
so i select node like below
var items = (from item in xmlDoc.Descendants("requestdate")
select item).ToList();
then i can update only requestdata tag value so do i have to repeat same for all tags or is there any good way to accomplish this.
Regards

There is an easy way to do this. This one is a hidden gem. Most people may not know this. This feature came in VS2013 and it's called "Paste XML as Classes."
Save your xml (Ex: MyXml.XML)
Create a new Console project
Open the Xml in Visual studio
Copy All contents of the xml (Ctl+A, Ctl + C)
Add a new class to your project. You can give any name you like.
Go to Edit>Paste Special>Paste XML as classes.
Add another class to your project. Then add below two methods to that class.
public static string Serialise<T>(T serialisableObject)
{
var doc = new XmlDocument();
using (var stream = new StringWriter())
{
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(xmlWriter, serialisableObject, ns);
doc.LoadXml(stream.ToString());
}
return doc.InnerXml;
}
public static T Deserialise<T>(string xml)
{
T list;
using (var reader = new StringReader(xml))
{
var serialiser = new XmlSerializer(typeof(T));
list = (T)serialiser.Deserialize(reader);
}
return list;
}
Then in your console applications Main method; add this.
var myObj = new adf();
myObj.prospect = new adfProspect();
myObj.prospect.customer = new adfProspectCustomer(){comments = "dgsrtetetete"};
//populate all fields.....
var xml = MySerializer.Serialise(myObj);
File.WriteAllText(#"C:\myNewXml.xml", xml);
That's it. Same way now you can deserialise an xml object in to your class.

Try the XmlSerializer class: https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx If you serialize/deserialize the xml then up dating is trivial.

If you wanted to change every phone number to "0123456789" you could do something like:
var xDoc = XDocument.Load("document.xml");
var results = from phone in xDoc.Descendants("phone") select phone;
foreach (XElement result in results)
{
element.SetValue("0123456789");
}

i have came up with solution with support two extension method i'm iterating all nodes and update.(since my xml is not too big or complicated this one would be a good solution)
with help of these two extension methods
public static void IterateThroughAllNodes(this XmlDocument doc, Action<XmlNode> elementVisitor)
{
if (doc != null && elementVisitor != null)
{
foreach (XmlNode node in doc.ChildNodes)
{
DoIterateNode(node, elementVisitor);
}
}
}
public static void IterateThrough(this XmlNodeList nodes, Action<XmlNode> elementVisitor)
{
if (nodes != null && elementVisitor != null)
{
foreach (XmlNode node in nodes)
{
DoIterateNode(node, elementVisitor);
}
}
}
private static void DoIterateNode(XmlNode node, Action<XmlNode> elementVisitor)
{
elementVisitor(node);
foreach (XmlNode childNode in node.ChildNodes)
{
DoIterateNode(childNode, elementVisitor);
}
}
then i can update my xml nodes as below
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/xmlmail.xml"));
var email = new XmlEmail();
doc.IterateThroughAllNodes(
delegate(XmlNode node)
{
if (node.Name.Equals("requestdate"))
node.InnerText= email.RequestDate.ToLongDateString();
if (node.Name.Equals("vehicle"))
{
XmlNodeList childs = node.ChildNodes;
childs.IterateThrough(delegate(XmlNode vnode)
{
if (vnode.Name.Equals("id"))
vnode.InnerText= email.VehicleId.ToString();
if (vnode.Name.Equals("year"))
vnode.InnerText= email.Year.ToString();
if (vnode.Name.Equals("make"))
vnode.InnerText= email.Make;
if (vnode.Name.Equals("model"))
vnode.InnerText= email.Model;
if (vnode.Name.Equals("vin"))
vnode.InnerText= email.Vin;
if (vnode.Name.Equals("trim"))
vnode.InnerText = email.Trim;
});
}
if (node.Name.Equals("customer"))
{
XmlNodeList childs = node.ChildNodes;
childs.IterateThrough(delegate(XmlNode vnode)
{
if (vnode.Attributes != null && (vnode.Name.Equals("name") && vnode.Attributes["part"].Value.Equals("first")))
vnode.InnerText= email.FirstName;
if (vnode.Attributes != null && (vnode.Name.Equals("name") && vnode.Attributes["part"].Value.Equals("last")))
vnode.InnerText= email.LastName;
if (vnode.Name.Equals("email"))
vnode.InnerText= email.Email;
if (vnode.Name.Equals("phone"))
vnode.InnerText= email.Phone;
if (vnode.Name.Equals("comments"))
vnode.InnerText= email.Comments;
if (vnode.Name.Equals("address"))
{
XmlNodeList addresschilds = vnode.ChildNodes;
addresschilds.IterateThrough(delegate(XmlNode anode)
{
if (anode.Name.Equals("street"))
anode.InnerText= email.Street;
if (anode.Name.Equals("city"))
anode.InnerText= email.City;
if (anode.Name.Equals("phone"))
anode.InnerText= email.Phone;
if (anode.Name.Equals("regioncode"))
anode.InnerText= email.RegionCode;
if (anode.Name.Equals("postalcode"))
anode.InnerText= email.Postalode;
if (anode.Name.Equals("country"))
anode.InnerText= email.Country;
});
}
});
}
});

Related

Append an existing child to the new child?

I have a xml file as:-
<Data>
<Caption>
</Caption>
</Data>
I added a new child CData in the the following code
foreach (XmlNode item in childNode.ChildNodes)
{
if (item.Name == "Data")
{
XmlCDataSection CData;
CData = xml2.CreateCDataSection("All Jane Austen novels 25% off starting 3/23!");
item.InsertBefore(CData, item.FirstChild);
foreach (XmlNode itemC in item.ChildNodes)
{
if (itemC.Name == "Caption")
{
XmlElement getTemplateID = xml2.CreateElement("TempalteID");
getTemplateID.InnerText = "10010";
itemC.AppendChild(getTemplateID);
//if (OptionsData[0].Key == "NoChilds")
//{
// XmlElement Getnochild = itemDoc.CreateElement("CaptionOptions");
// Getnochild.InnerText = "";
// itemC.AppendChild(Getnochild);
//}
//else
//{
XmlNode elemCap = xml2.CreateNode(XmlNodeType.Element, "CaptionOptions", null);
itemC.AppendChild(elemCap);
XmlElement Getelem1 = xml2.CreateElement("CaptionField");
elemCap.AppendChild(Getelem1);
XmlElement elem2 = xml2.CreateElement("FieldID");
XmlElement elem3 = xml2.CreateElement("FieldID");
elem2.InnerText = "#FieldId1";
elem3.InnerText = "#FieldId2";
XmlElement elem4 = xml2.CreateElement("TextString");
XmlElement elem5 = xml2.CreateElement("TextString");
elem4.InnerText = "#TextString1";
elem5.InnerText = "#TextString2";
Getelem1.AppendChild(elem2);
Getelem1.AppendChild(elem4);
Getelem1.AppendChild(elem3);
Getelem1.AppendChild(elem5);
//}
}
}
}
}
Now my final xml is coming as
<Data>
<![CDATA[All Jane Austen novels 25% off starting 3/23!]]>
<Caption>
<TempalteID>10010</TempalteID>
<CaptionOptions><CaptionField>
<FieldID>#FieldId1</FieldID>
<TextString>#TextString1</TextString>
<FieldID>#FieldId2</FieldID>
<TextString>#TextString2</TextString>
</CaptionField></CaptionOptions>
</Caption>
</Data>
But I want to make it as the following way....
<Data><![CDATA[<Caption xmlns="http://www.iin.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.happy.xsd">
<TemplateID>T000114-NOW</TemplateID>
<CaptionOptions>
<CaptionField>
<FieldID>NOW1</FieldID>
<TextString>"Ep 01"</TextString>
</CaptionField>
<CaptionField>
<FieldID>NOW2</FieldID>
<TextString>""</TextString>
</CaptionField>
</CaptionOptions>
</Caption>]]>
</Data>
So as you can see I basically wanted my newly added child CData to make <Caption> as it's child. So basically I want to create a child and make an existing child as it's child.(But I don't think I would still get the same format?")
How to do it?
Using xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.InteropServices;
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
string xml = "<Data><Caption xmlns=\"http://www.iin.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.happy.xsd\"/></Data>";
XDocument doc = XDocument.Parse(xml);
XElement caption = doc.Descendants("Data").FirstOrDefault();
caption.Add(new XElement("TemplateID","T000114-NOW"));
XElement options = new XElement("CaptionOptions");
caption.Add(options);
foreach (Field field in Field.fields)
{
XElement newField = new XElement("CaptionField", new object[] { new XElement("FieldID", field.ID), new XElement("TextString", field.text)});
options.Add(newField);
}
}
}
public class Field
{
public static List<Field> fields = new List<Field>() {
new Field() { ID = "NOW1", text = "Ep 01"},
new Field() { ID = "Ep 01", text = ""}
};
public string ID { get; set; }
public string text { get; set; }
}
}
If I understand right, what you want to do is storing XML data in CDATA element. I want to remind you, that this is not what CDATA was intended to be used for, but here is example how to do that:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
//Add the new node to the document.
XmlElement root = doc.DocumentElement;
XmlCDataSection CData;
CData = doc.CreateCDataSection(root.InnerXml);
root.RemoveAll();
root.AppendChild(CData);
doc.Save(Console.Out);

c# to read xml file and update the checkboxes with the nodes

I have an xml file like this:
<servers>
<general name="1">
<service name="ser1"/>
<service name="ser2"/>
</general>
<general name="2">
<service name="ser1"/>
<service name="ser2"/>
</general>
</servers>
In my winform application, I have a treeview list with checkbox property set to true.What I am trying to achieve is that I am attempting to read this xml file and update both the parent and child node to this tree view.
What I have tried is:
XDocument doc = XDocument.Load(#"D:\\path.xml");
TreeNode node;
var gnrl = from general in doc.Descendants("general")
select new
{
parent = general.Attribute("name").Value,
child = general.Descendants("service")
};
//Loop through results
foreach (var general in gnrl)
{
// Add a root node.
node = dcselectview.Nodes.Add(String.Format(general.parent));
foreach (var ser in general.child)
{
// Add a node as a child of the previously added node.
node = node.Nodes.Add(String.Format(ser.Attribute("name").Value));
}
}
it reads the file and all details are updated but not in a proper way. rather it is shown as below:
Needed:
I want the parent element to be on top and down-right to it,the child elements. If possible, it would be nice if I dont have checkboxes for parent elements.
Any help would be really appreciated..
EDIT:
My code edited. Now I am getting as shown in new picture below:
I want the 2 black lines to be in same line,not as child node of another..
Do you want a hierarchical structure, like this?
If so, I recommend you to look at the Treeview:
http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.checkboxes.aspx
Try this you will get
XDocument doc = XDocument.Load(#"D:\\test.xml");
IEnumerable<XElement> Xele = doc.XPathSelectElements("//general");
foreach (XElement xe in Xele.Descendants())
{
//MessageBox.Show(xe.Attribute("name").Value);
dcselectview.Parent.Text =xe.Parent.Attribute("name").Value; // here parent value ----> name="1" and name="2"
dcselectview.Nodes.Add(xe.Attribute("name").Value); // ser1 ser2 ser1 ser2
}
Try this:
public static class TreeViewExtension
{
public static bool LoadNodesFromXML(this TreeView tv, string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
TreeNode rootNode = new TreeNode();
rootNode.Text = doc.Root.ToString().Split('>')[0] + ">";
rootNode.LoadTreeNodes(doc.Root.Elements());
tv.Nodes.Add(rootNode);
return true;
}
catch { return false; }
}
public static void LoadTreeNodes(this TreeNode parentNode, IEnumerable<XElement> elements)
{
foreach (var e in elements) {
TreeNode childNode = new TreeNode();
childNode.Text = e.ToString().Split('>')[0] + ">";
parentNode.Nodes.Add(childNode);
childNode.LoadTreeNodes(e.Elements());
}
}
}
//Usage:
var yourInputXMLString = "<servers><general name=\"1\"><service name=\"ser1\"/>" +
"<service name=\"ser2\"/></general><general name=\"2\">" +
"<service name=\"ser1\"/><service name=\"ser2\"/>" +
"</general></servers>";
treeView1.LoadNodesFromXML(yourInputXMLString);
You have to add parent as a node first
public static bool LoadNodesFromXML()
{
XDocument doc = XDocument.Load(#"D:\\path.xml");
var root = doc.Root;
var childenode = dcselectview.Nodes.Add(root.Attribute("Name").Value);
foreach (var xElement in root .Elements())
{
InsertNode(childenode, xElement);
}
}
private void InsertNode(TreeNode parent, XElement element)
{
var childenode = parent.Nodes.Add(element.Attribute("Name").Value);
if(element.Elements().Count() > 0)
foreach (var xElement in element.Elements())
{
InsertNode(childenode, xElement);
}
}
Thanks all for your help::But I have found another solution of my own::
XDocument doc = XDocument.Load(#"path\\test.xml");
// Add nodes to treeView1.
TreeNode pnode;
TreeNode cnode;
var gnrl = from general in doc.Descendants("general")
select new
{
parent = general.Attribute("name").Value,
child = general.Descendants("service")
};
//Loop through results
foreach (var general in gnrl)
{
// Add a root node.
pnode = treeview.Nodes.Add(String.Format(general.parent));
foreach (var ser in general.child)
{
// Add a node as a child of the previously added node.
cnode = pnode.Nodes.Add(String.Format(ser.Attribute("name").Value));
}
}

How to set a value in XML using C#?

How to change the value of sourcePatientInfo in the following xml file using c#.
I can able to read the value using,
var elem = (from n in xml.Descendants("Slot")
where n.Attribute("name").Value == "sourcePatientInfo"
select n).FirstOrDefault();
How to change the same using C#?
<?xml version="1.0" encoding="utf-8"?>
<rs:SubmitObjectsRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rs="urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1" xmlns:rim="urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1" xmlns="urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1">
<LeafRegistryObjectList>
<ObjectRef id="urn:uuid:93606bcf-9494-43ec-9b4e-a7748d1a838d" />
<ExtrinsicObject id="Document01" mimeType="application/dicom" objectType="urn:uuid:7edca82f-054d-47f2-a032-9b2a5b5186c1">
<Name>
<LocalizedString value="Physical" />
</Name>
<Description />
<Slot name="sourcePatientId">
<ValueList>
<Value>pid1^^^&1.2.3&ISO</Value>
</ValueList>
</Slot>
<Slot name="sourcePatientInfo">
<ValueList>
<Value>PID-3|pid1^^^&1.2.3&ISO</Value>
<Value>PID-5|Doe^John^^^</Value>
<Value>PID-7|19560527</Value>
<Value>PID-8|M</Value>
<Value>PID-11|100 Main St^^Metropolis^Il^44130^USA</Value>
</ValueList>
</Slot>
I would like to change the values using c#. Am not able to figure out the way. Any Help to resolve this issue will be appreciated.
I want to change the
<Slot name="sourcePatientInfo">
<ValueList>
<Value>PID-3|pid1^^^&1.2.3&ISO</Value>
<Value>PID-5|Doe^John^^^</Value>
to the following value
<Slot name="sourcePatientInfo">
<ValueList> <Value>PID-3|MyPID</Value>
<Value>PID-5|MyName</Value>
I have also tried the following the code,
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc1.NameTable);
namespaceManager.AddNamespace("rs", "urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1");
var query = "/rs:SubmitObjectsRequest/LeafRegistryObjectList/ExtrinsicObject";
XmlNodeList nodeList = xmlDoc1.SelectNodes(query, namespaceManager);
foreach (XmlNode node1 in nodeList)
{
if (node1.Attributes["Slot"].Value == "sourcePatientInfo")
{
node1.Attributes["ValueList"].Value = "Myvalue";
}
}
In this code, nodelist.count is always zero :-(. Kindly help me to resolve the issue.
If you need to update first two values:
var slot = xml.Descendants("Slot")
.Where(n => n.Attribute("name").Value == "sourcePatientInfo")
.FirstOrDefault();
if(slot == null)
{
throw new WhateverAppropriateHereEcxeption();
}
var values = slot.Descendants("Value").ToList();
if(values.Count < 2)
{
throw new WhateverAppropriateHereEcxeption();
}
values[0].Value = "PID-3|MyPID" // updating the first value
values[1].Value = "PID-5|MyName" // updating the second value
if you have to search by value you can do:
bool UpdateValue(XElement slot, string oldValue, string newValue)
{
var elem = slot.Descendants("Slot")
.Where(n => n.Name == "Value" && n.Value == oldValue)
.FirstOrDefault();
if(elem != null)
{
elem = newValue;
return true;
}
return false;
}
and inside some function
var slot = xml.Descendants("Slot")
.Where(n => n.Attribute("name").Value == "sourcePatientInfo")
.FirstOrDefault();
if(slot == null)
{
throw new WhateverAppropriateHereEcxeption();
}
UpdateValue(slot, "PID-3|pid1^^^&1.2.3&ISO", "PID-3|MyPID");
UpdateValue(slot, "PID-5|Doe^John^^^", "PID-5|MyName");
UPD when you call xml.Descendants("Slot") xml look only for elements in default namespace. I use an extension method as a quick workaround to avoid that:
public static IEnumerable<XElement> NsDescendants(this XContainer e, string elementName)
{
return e.Descendants().Where(d => d.Name.LocalName == elementName);
}
Finally my problem is solved with the following code.
XmlDocument xmlDocSOR = new XmlDocument();
XmlDocSOR.Load("filename.xml");
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocSOR.NameTable);
namespaceManager.AddNamespace("rs", "urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1");
namespaceManager.AddNamespace("ns", "urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1");
var query = "/rs:SubmitObjectsRequest/ns:LeafRegistryObjectList/ns:ExtrinsicObject/ns:Slot";
XmlNodeList nodeList = xmlDocSOR.SelectNodes(query, namespaceManager);
foreach (XmlNode plainnode in nodeList)
{
if (plainnode.Attributes["name"].Value == "sourcePatientId")
{
XmlNode childnode = plainnode.LastChild;
XmlElement ee1 = (XmlElement)childnode.FirstChild;
ee1.InnerText = sPatientID;
}
}
xmlDocSOR.Save("filename.xml");

Filtering by higher nodes attributes linq

I am trying to serialize and insert a new created object into a specific child node of an XDocument. I've managed to accomplish this but my code seems smelly.
How can I test against a higher nodes attribute value without chaining through the Parent property like I have done below?
XDocument xdoc = XDocument.Load(path);
var elements = (
from doc in xdoc.Descendants("Unit")
where doc.Parent.Parent.Attribute("name").Value == _UnitTypeName &&
doc.Parent.Parent.Parent.Parent.Attribute("name").Value == _UnitCategoryN
doc.Parent.Parent.Parent.Parent.Parent.Parent.Attribute("name").Value ==
select doc
);
foreach (var element in elements)
{
Unit unit =
new Unit
{
Armour = _Armour,
Attacks = _Attacks,
BallisticSkill = _BallisticSkill,
Composition = _Composition,
DedicatedTransport = _DedicatedTransport,
Initiative = _Initiative,
Leadership = _Leadership,
Options = _Options,
SaveThrow = _SaveThrow,
SpecialRules = _SpecialRules,
Strength = _Strength,
Toughness = _Toughness,
UnitName = _UnitName,
Weapons = _Weapons,
WeaponSkill = _WeaponSkill,
Wounds = _Wounds,
Points = _Points
};
XmlSerializer serializer = new XmlSerializer(typeof(Unit));
using (var stream = new MemoryStream())
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(stream, unit, ns);
stream.Position = 0;
//using (XmlReader reader = XmlReader.Create(stream))
//{
// XElement xe = XElement.Load(reader);
XElement xe = XElement.Load(#"C:\Test\tempfile.xml"); // For some reason loading via MemoryStream messes with xml formatting
element.AddBeforeSelf(xe);
//}
}
break;
}
xdoc.Save(path);
This is the structure of the XML Document:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfArmy>
<Army name="Tyranid">
<unit-category>
<UnitCategory name="Troops">
<unit-type>
<UnitType name="Infantry">
<unit>
<Unit points="5" name="Hornmagant" composition="20" weapon-skill="3" ballistic-skill="100" strength="3" toughness="4" wounds="1" initiative="3" attacks="3" leadership="5" saving-throw="6+" armour="Chitin" weapons="Many" special-rules="None" dedicated-transport="No" options="8">
<Amount>0</Amount>
</Unit>
<Unit points="5" name="Termagant" composition="20" weapon-skill="3" ballistic-skill="100" strength="3" toughness="4" wounds="1" initiative="3" attacks="3" leadership="5" saving-throw="6+" armour="Chitin" weapons="Many" special-rules="None" dedicated-transport="No" options="8">
<Amount>0</Amount>
</Unit>
</unit>
</UnitType>
</unit-type>
</UnitCategory>
</unit-category>
</Army>
</ArrayOfArmy>
You can use compound from clauses, which is similar to using nested foreach loops:
var elements = (
from army in xdoc.Descendants("Army")
where army.Attribute("name").Value == _ArmyName
from unitCategory in army.Descendants("UnitCategory")
where unitCategory.Attribute("name").Value == _UnitCategoryName
from unitType in unitCategory.Descendants("UnitType")
where unitType.Attribute("name").Value == _UnitTypeName
from unit in unitType.Descendants("Unit")
select unit
);
Note: the method syntax equivalent is SelectMany().

How to convert JSON to XML or XML to JSON?

I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to XML format and viceversa?
Yes. Using the JsonConvert class which contains helper methods for this precise purpose:
// To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
Documentation here: Converting between JSON and XML with Json.NET
Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:
XML -> JSON
All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null
A new update changes how null can be handled (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm
JSON -> XML
You need a top level object that will convert to a root XML element or the parser will fail.
Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.
Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.
You can do these conversions also with the .NET Framework:
JSON to XML: by using System.Runtime.Serialization.Json
var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));
XML to JSON: by using System.Web.Script.Serialization
var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));
private static Dictionary<string, object> GetXmlData(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
I'm not sure there is point in such conversion (yes, many do it, but mostly to force a square peg through round hole) -- there is structural impedance mismatch, and conversion is lossy. So I would recommend against such format-to-format transformations.
But if you do it, first convert from json to object, then from object to xml (and vice versa for reverse direction). Doing direct transformation leads to ugly output, loss of information, or possibly both.
Thanks for David Brown's answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:
XmlNode myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString); // is node not note
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);
I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:
public XmlDocument JsonToXML(string json)
{
XmlDocument doc = new XmlDocument();
using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
{
XElement xml = XElement.Load(reader);
doc.LoadXml(xml.ToString());
}
return doc;
}
Note: I wanted an XmlDocument rather than an XElement for xPath purposes.
Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.
Here is the full c# code to convert xml to json
public static class JSon
{
public static string XmlToJSON(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return XmlToJSON(doc);
}
public static string XmlToJSON(XmlDocument xmlDoc)
{
StringBuilder sbJSON = new StringBuilder();
sbJSON.Append("{ ");
XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
sbJSON.Append("}");
return sbJSON.ToString();
}
// XmlToJSONnode: Output an XmlElement, possibly as part of a higher array
private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
sbJSON.Append("{");
// Build a sorted list of key-value pairs
// where key is case-sensitive nodeName
// value is an ArrayList of string or XmlElement
// so that we know whether the nodeName is an array or not.
SortedList<string, object> childNodeNames = new SortedList<string, object>();
// Add in all node attributes
if (node.Attributes != null)
foreach (XmlAttribute attr in node.Attributes)
StoreChildNode(childNodeNames, attr.Name, attr.InnerText);
// Add in all nodes
foreach (XmlNode cnode in node.ChildNodes)
{
if (cnode is XmlText)
StoreChildNode(childNodeNames, "value", cnode.InnerText);
else if (cnode is XmlElement)
StoreChildNode(childNodeNames, cnode.Name, cnode);
}
// Now output all stored info
foreach (string childname in childNodeNames.Keys)
{
List<object> alChild = (List<object>)childNodeNames[childname];
if (alChild.Count == 1)
OutputNode(childname, alChild[0], sbJSON, true);
else
{
sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
foreach (object Child in alChild)
OutputNode(childname, Child, sbJSON, false);
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" ], ");
}
}
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" }");
}
// StoreChildNode: Store data associated with each nodeName
// so that we know whether the nodeName is an array or not.
private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
{
// Pre-process contraction of XmlElement-s
if (nodeValue is XmlElement)
{
// Convert <aa></aa> into "aa":null
// <aa>xx</aa> into "aa":"xx"
XmlNode cnode = (XmlNode)nodeValue;
if (cnode.Attributes.Count == 0)
{
XmlNodeList children = cnode.ChildNodes;
if (children.Count == 0)
nodeValue = null;
else if (children.Count == 1 && (children[0] is XmlText))
nodeValue = ((XmlText)(children[0])).InnerText;
}
}
// Add nodeValue to ArrayList associated with each nodeName
// If nodeName doesn't exist then add it
List<object> ValuesAL;
if (childNodeNames.ContainsKey(nodeName))
{
ValuesAL = (List<object>)childNodeNames[nodeName];
}
else
{
ValuesAL = new List<object>();
childNodeNames[nodeName] = ValuesAL;
}
ValuesAL.Add(nodeValue);
}
private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
if (alChild == null)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
sbJSON.Append("null");
}
else if (alChild is string)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
string sChild = (string)alChild;
sChild = sChild.Trim();
sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
}
else
XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
sbJSON.Append(", ");
}
// Make a string safe for JSON
private static string SafeJSON(string sIn)
{
StringBuilder sbOut = new StringBuilder(sIn.Length);
foreach (char ch in sIn)
{
if (Char.IsControl(ch) || ch == '\'')
{
int ich = (int)ch;
sbOut.Append(#"\u" + ich.ToString("x4"));
continue;
}
else if (ch == '\"' || ch == '\\' || ch == '/')
{
sbOut.Append('\\');
}
sbOut.Append(ch);
}
return sbOut.ToString();
}
}
To convert a given XML string to JSON, simply call XmlToJSON() function as below.
string xml = "<menu id=\"file\" value=\"File\"> " +
"<popup>" +
"<menuitem value=\"New\" onclick=\"CreateNewDoc()\" />" +
"<menuitem value=\"Open\" onclick=\"OpenDoc()\" />" +
"<menuitem value=\"Close\" onclick=\"CloseDoc()\" />" +
"</popup>" +
"</menu>";
string json = JSON.XmlToJSON(xml);
// json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}
For convert JSON string to XML try this:
public string JsonToXML(string json)
{
XDocument xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", ""));
XElement root = new XElement("Root");
root.Name = "Result";
var dataTable = JsonConvert.DeserializeObject<DataTable>(json);
root.Add(
from row in dataTable.AsEnumerable()
select new XElement("Record",
from column in dataTable.Columns.Cast<DataColumn>()
select new XElement(column.ColumnName, row[column])
)
);
xmlDoc.Add(root);
return xmlDoc.ToString();
}
For convert XML to JSON try this:
public string XmlToJson(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
return jsonText;
}
Here is a simple snippet that converts a XmlNode (recursively) into a hashtable, and groups multiple instances of the same child into an array (as an ArrayList).
The Hashtable is usually accepted to convert into JSON by most of the JSON libraries.
protected object convert(XmlNode root){
Hashtable obj = new Hashtable();
for(int i=0,n=root.ChildNodes.Count;i<n;i++){
object result = null;
XmlNode current = root.ChildNodes.Item(i);
if(current.NodeType != XmlNodeType.Text)
result = convert(current);
else{
int resultInt;
double resultFloat;
bool resultBoolean;
if(Int32.TryParse(current.Value, out resultInt)) return resultInt;
if(Double.TryParse(current.Value, out resultFloat)) return resultFloat;
if(Boolean.TryParse(current.Value, out resultBoolean)) return resultBoolean;
return current.Value;
}
if(obj[current.Name] == null)
obj[current.Name] = result;
else if(obj[current.Name].GetType().Equals(typeof(ArrayList)))
((ArrayList)obj[current.Name]).Add(result);
else{
ArrayList collision = new ArrayList();
collision.Add(obj[current.Name]);
collision.Add(result);
obj[current.Name] = collision;
}
}
return obj;
}
Try this function. I just wrote it and haven't had much of a chance to test it, but my preliminary tests are promising.
public static XmlDocument JsonToXml(string json)
{
XmlNode newNode = null;
XmlNode appendToNode = null;
XmlDocument returnXmlDoc = new XmlDocument();
returnXmlDoc.LoadXml("<Document />");
XmlNode rootNode = returnXmlDoc.SelectSingleNode("Document");
appendToNode = rootNode;
string[] arrElementData;
string[] arrElements = json.Split('\r');
foreach (string element in arrElements)
{
string processElement = element.Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
if ((processElement.IndexOf("}") > -1 || processElement.IndexOf("]") > -1) && appendToNode != rootNode)
{
appendToNode = appendToNode.ParentNode;
}
else if (processElement.IndexOf("[") > -1)
{
processElement = processElement.Replace(":", "").Replace("[", "").Replace("\"", "").Trim();
newNode = returnXmlDoc.CreateElement(processElement);
appendToNode.AppendChild(newNode);
appendToNode = newNode;
}
else if (processElement.IndexOf("{") > -1 && processElement.IndexOf(":") > -1)
{
processElement = processElement.Replace(":", "").Replace("{", "").Replace("\"", "").Trim();
newNode = returnXmlDoc.CreateElement(processElement);
appendToNode.AppendChild(newNode);
appendToNode = newNode;
}
else
{
if (processElement.IndexOf(":") > -1)
{
arrElementData = processElement.Replace(": \"", ":").Replace("\",", "").Replace("\"", "").Split(':');
newNode = returnXmlDoc.CreateElement(arrElementData[0]);
for (int i = 1; i < arrElementData.Length; i++)
{
newNode.InnerText += arrElementData[i];
}
appendToNode.AppendChild(newNode);
}
}
}
return returnXmlDoc;
}
I did like David Brown said but I got the following exception.
$exception {"There are multiple root elements. Line , position ."} System.Xml.XmlException
One solution would be to modify the XML file with a root element but that is not always necessary and for an XML stream it might not be possible either. My solution below:
var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, #"..\..\App_Data"));
var directoryInfo = new DirectoryInfo(path);
var fileInfos = directoryInfo.GetFiles("*.xml");
foreach (var fileInfo in fileInfos)
{
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(fileInfo.FullName, settings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
var node = doc.ReadNode(reader);
string json = JsonConvert.SerializeXmlNode(node);
}
}
}
}
Example XML that generates the error:
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
I have used the below methods to convert the JSON to XML
List <Item> items;
public void LoadJsonAndReadToXML() {
using(StreamReader r = new StreamReader(# "E:\Json\overiddenhotelranks.json")) {
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject <List<Item>> (json);
ReadToXML();
}
}
And
public void ReadToXML() {
try {
var xEle = new XElement("Items",
from item in items select new XElement("Item",
new XElement("mhid", item.mhid),
new XElement("hotelName", item.hotelName),
new XElement("destination", item.destination),
new XElement("destinationID", item.destinationID),
new XElement("rank", item.rank),
new XElement("toDisplayOnFod", item.toDisplayOnFod),
new XElement("comment", item.comment),
new XElement("Destinationcode", item.Destinationcode),
new XElement("LoadDate", item.LoadDate)
));
xEle.Save("E:\\employees.xml");
Console.WriteLine("Converted to XML");
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
I have used the class named Item to represent the elements
public class Item {
public int mhid { get; set; }
public string hotelName { get; set; }
public string destination { get; set; }
public int destinationID { get; set; }
public int rank { get; set; }
public int toDisplayOnFod { get; set; }
public string comment { get; set; }
public string Destinationcode { get; set; }
public string LoadDate { get; set; }
}
It works....
Cinchoo ETL - an open source library available to do the conversion of Xml to JSON easily with few lines of code
Xml -> JSON:
using (var p = new ChoXmlReader("sample.xml"))
{
using (var w = new ChoJSONWriter("sample.json"))
{
w.Write(p);
}
}
JSON -> Xml:
using (var p = new ChoJsonReader("sample.json"))
{
using (var w = new ChoXmlWriter("sample.xml"))
{
w.Write(p);
}
}
Sample fiddle: https://dotnetfiddle.net/enUJKu
Checkout CodeProject articles for some additional help.
Disclaimer: I'm the author of this library.
Here's an example of how to convert JSON to XML using .NET built-in libraries (instead of 3rd party libraries like Newtonsoft).
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Xml.Linq;
XDocument xmlDoc = jsonToXml(jsonObj);
private XDocument jsonToXml(JsonObject obj)
{
var xmlDoc = new XDocument();
var root = new XElement("Root");
xmlDoc.Add(root);
foreach (var prop in obj)
{
var xElement = new XElement(prop.Key);
xElement.Value = prop.Value.ToString();
root.Add(xElement);
}
return xmlDoc;
}

Categories