//--- Class Methods --- private static void WriteJson(XmlNode node, TextWriter writer) { bool first = true; switch (node.NodeType) { case XmlNodeType.Document: writer.Write("{"); WriteJson(XDoc.NewListXmlNode(node.ChildNodes), writer); writer.Write("}"); break; case XmlNodeType.Element: // check if we have the common case of a simple node (tag and text only without attributes, or tag only without text or attributes) if ((node.Attributes.Count == 0) && (node.ChildNodes.Count == 0)) { writer.Write("\"\""); } else if ((node.Attributes.Count > 0) || (node.ChildNodes.Count != 1) || (node.ChildNodes[0].NodeType != XmlNodeType.Text)) { writer.Write("{"); foreach (XmlNode sub in node.Attributes) { if (!first) { writer.Write(","); } WriteJson(sub, writer); first = false; } if (!first && (node.ChildNodes.Count > 0)) { writer.Write(","); } WriteJson(XDoc.NewListXmlNode(node.ChildNodes), writer); writer.Write("}"); } else { WriteJson(node.ChildNodes[0], writer); } break; case XmlNodeType.Text: writer.Write(XDocUtil.EncodeXmlString(node.Value)); break; case XmlNodeType.Attribute: writer.Write("{0}:{1}", XDocUtil.EncodeXmlString("@" + node.Name), XDocUtil.EncodeXmlString(node.Value)); break; } }
private static void WriteJson(XmlNode[] nodes, TextWriter writer) { IDictionary <string, List <XmlNode> > elems = XDocUtil.CollapseNodeList(nodes); bool firstOuter = true; foreach (KeyValuePair <string, List <XmlNode> > entry in elems) { if (!firstOuter) { writer.Write(","); } writer.Write("{0}:", XDocUtil.EncodeXmlString(entry.Key)); if (entry.Value.Count > 1) { writer.Write("["); bool firstInner = true; foreach (XmlNode node in entry.Value) { if (!firstInner) { writer.Write(","); } if (node.NodeType == XmlNodeType.Text) { writer.Write(XDocUtil.EncodeXmlString(node.Value)); } else { WriteJson(node, writer); } firstInner = false; } writer.Write("]"); } else { WriteJson(entry.Value[0], writer); } firstOuter = false; } }