Example of XML-to-JSON method conversion in ASP. NET, xmljson

Source: Internet
Author: User

Example of XML-to-JSON method conversion in ASP. NET, xmljson

This article describes how to convert XML to JSON in ASP. NET. The details are as follows:

Generally, data is stored in XML format in many applications, and data is sent to the client in JSON format for further processing. To achieve this, they must convert the XML format to the JSON format.

The code for converting XML to JSON is as follows:

Copy codeThe Code is as follows: private 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 childNodeNames = new SortedList ();

// 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)
{
ArrayList alChild = (ArrayList) 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 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
Object oValuesAL = childNodeNames [nodeName];
ArrayList ValuesAL;
If (oValuesAL = null)
{
ValuesAL = new ArrayList ();
ChildNodeNames [nodeName] = ValuesAL;
}
Else
ValuesAL = (ArrayList) oValuesAL;
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 ();
}

I hope this article will help you design your asp.net program.


How does aspnet send and receive json or xml data using jquery? The key is the conversion problem. For example, how to convert the control values to jason

Upload the information to be collected using ajax setquerystring to the background at the front end,
The backend uses formcollection to receive and process foreground information,
After processing, a return value of the json type is returned,
The foreground uses setsuccess to obtain and use json.
That's the process ..

Use C # To convert XML into JSON code

You can convert xml into a able and then convert it to JSON.
DataSet (DataTable) and XML Conversion: blog.csdn.net/...5.aspx

Public static string DataTableToJSON (DataTable table)
{
StringBuilder json = new StringBuilder ();
Json. Append ("[");
For (int I = 0; I <table. Rows. Count; I ++)
{
DataRow row = table. Rows [I];

// Json object
Json. Append ("{");
For (int j = 0; j <table. Columns. Count; j ++)
{
String columnName = table. Columns [j]. ColumnName;
String columnType = table. Columns [j]. DataType. Name;

// Json field
If (columnType = "Int32" | columnType = "Int16" | columnType = "Decimal ")
{
// Don't surround numbers with quotes
Json. AppendFormat ("\" {0} \ ": \" {1} \ "", columnName, row. IsNull (columnName )? "": Row [columnName]);
}
Else if (columnType = "Boolean ")
{
// Make the bool value lowercase
Json. AppendFormat ("\" {0} \ ": {1 ...... the remaining full text >>>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.