C# XML转Json

c# Xml 和 Json 转换方法记录 以上代码分别使用了Newtonsoft.Json库和System.Xml.Serialization库,效果相同但实现方式不同。第一种方法使用XmlSerializer将JSON对象直接序列化为XML,适用于简单数据结构。第二种方法使用JObject解析JSON,然后使用XDocument和XElement将解析结果转换为XML,适用于复杂数据结构。上述代码中,将XML转换为JSON时,使用了第三方库Newtonsoft.Json或者系统自带库System.Text.Json。c# xml 转 json。 阅读详情

Json使用第三方的LightJson


第一次提交的很多问题,在此表示歉意,这一次的应该不会让你失望。


由于目前公司的xml文件不标准,使用微软的XmlDocument的load就崩溃了,主要是里面有类似: x = 1或y=2导致,所以只能自己解析。

由于xml有如下格式:

1. <demo x=1 y="z">demo xxx </demo>,会把demo xxx 和一个固定的key(xml_inner_text)组合。

2. <demo2>demo 2</demo2>,会把demo 2和key(demo2)组合。

3. InnerText

<Description Format="FooFormat">
	desc_inner text
	line-2
	line-3
	line-4
</Description>

会把>和</之间的内容用\r\n连接,不想的话可以改。



先上效果,如果不是你想要的就关了本页面:

原始xml:

<?xml version="1.0"?>
<!DOCTYPE Test>
<Tests>
	<s_tes>
	</s_tes>
	<s_tes>asdf
	</s_tes>
	<s_tes x= 1 y = 2>asdf1111
	</s_tes>
	<singlelineclose/>
	<singlelineclose ads="111"/>
	<singlelineclose ads="111 y =  56   "/>
	<singlelineclose ads="111" y =  56   />
	<singlelineclose1 ads1="111"/>
	<abc x=1 y=2 z= 3></abc>
	<abc x1=1 y1=2 z1= 3>abc-1</abc>
	<abc x1=1 y1=2 z1=3 >abc-1</abc>
	<abc>abc-1</abc>
	<U x=1 FileName="a1\b2\c3\d4\e.s" m = 	2	 y = " y1 y2 " #z_ = " @z 2 " you=12> u test 
		U_1
	</U>
	<subtree col=3 row=5 ident=42 FileName="aa\bb\cc\dd\e1.s">
	</subtree>
	<demo x=1 y="z">demo xxx </demo>
	<demo1>demo1-1
		demo1-1
	</demo1>
	<demo2>demo 2</demo2>
  <Test Name="The First Test" x=1  y = "abc">
    <SomeText>Some simple text</SomeText>
    <SomeMoreText>More text</SomeMoreText>
    <Description Format="FooFormat">
    	desc_inner text
    	line-2
    	line-3
    	line-4
    </Description>
  </Test>
  <Test Name="Second"/>
  <otherTag0>
  </otherTag0>
  <otherTag1>abc
  </otherTag1>
  <Test Name="Third"/>
  <Test Name="Four">
  	<FourSon Name="FourSon"/>
  </Test>
</Tests>


转换后的Json:

{
	"Tests": {
		"s_tes": [
			{
			},
			"asdf",
			{
				"x": "1",
				"y": "2",
				"xml_inner_text": "asdf1111"
			}
		],
		"singlelineclose": [
			{
			},
			{
				"ads": "111"
			},
			{
				"ads": "111 y =  56   "
			},
			{
				"ads": "111",
				"y": "56"
			}
		],
		"singlelineclose1": {
			"ads1": "111"
		},
		"abc": [
			{
				"x1": "1",
				"y1": "2",
				"z1": "3",
				"xml_inner_text": "abc-1"
			},
			{
				"x1": "1",
				"y1": "2",
				"z1": "3",
				"xml_inner_text": "abc-1"
			},
			"abc-1"
		],
		"U": {
			"x": "1",
			"FileName": "a1\\b2\\c3\\d4\\e.s",
			"m": "2",
			"y": " y1 y2 ",
			"#z_": " @z 2 ",
			"you": "12",
			"xml_inner_text": " u test\r\nU_1"
		},
		"subtree": {
			"col": "3",
			"row": "5",
			"ident": "42",
			"FileName": "aa\\bb\\cc\\dd\\e1.s"
		},
		"demo": {
			"x": "1",
			"y": "z",
			"xml_inner_text": "demo xxx "
		},
		"demo1": "demo1-1\r\ndemo1-1",
		"demo2": "demo 2",
		"Test": [
			{
				"Name": "The First Test",
				"x": "1",
				"y": "abc",
				"SomeText": "Some simple text",
				"SomeMoreText": "More text",
				"Description": {
					"Format": "FooFormat",
					"xml_inner_text": "desc_inner text\r\nline-2\r\nline-3\r\nline-4"
				}
			},
			{
				"Name": "Second"
			},
			{
				"Name": "Third"
			},
			{
				"Name": "Four",
				"FourSon": {
					"Name": "FourSon"
				}
			}
		],
		"otherTag0": {
		},
		"otherTag1": "abc"
	}
}



辅助类:

TextUtil:

public static class TextUtil
{
	public static bool IsXmlHeader(string input)
	{
		string pattern = @"^<?.*?\?>{1,1}$";

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			return true;
		}

		pattern = @"^<!DOCTYPE.*?>$";
		match = Regex.Match(input, pattern);
		if (match.Success)
		{
			return true;
		}

		return false;
	}

	public static bool IsXmlTagStart(string input, out string tagName) // <abc>
	{
		//string pattern = @"^<{1,1}/{0,0}(.+)?>{1,1}\B";
		//string pattern = @"^<{1,1}/{0,0}\w*>{1,1}\B";
		string pattern = @"^<\w+>$";

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			int p_s = match.Value.IndexOf("<");
			int p_e = match.Value.LastIndexOf(">");
			if ((-1 == p_s) || (-1 == p_e))
			{
				tagName = null;
				return false;
			}

			tagName = match.Value.Substring(p_s + 1, p_e - p_s - 1).Trim();
			return true;
		}

		tagName = null;
		return false;
	}

	private static bool SplitXmlTagAndAttribute(ref string input, string endstr, out string tagName, out List<KeyValuePair<string, string>> attributePairs)
	{
		int endLen = endstr.Length;
		int tagLen;
		string xml;

		tagName = null;
		attributePairs = null;

		string pattern = @"^<\w+\b";
		Match match = Regex.Match(input, pattern);
		if (!match.Success)
		{
			return false;
		}

		tagName = match.Value.Substring(1); // 除<
		tagLen = tagName.Length;

		//xml = input.Substring(tagLen + 1, input.Length - tagLen - endLen - 1).Trim();
		xml = input.Substring(tagLen + 1).TrimStart();

		int pos = -1;
		string key;
		string value="";

		do
		{
			pos = xml.IndexOf("=");
			if (-1 == pos)
			{
				break;
			}

			key = xml.Substring(0, pos).Trim();
			xml = xml.Substring(pos + 1).TrimStart();
			if ('"' == xml[0])
			{
				pos = xml.IndexOf('"', 1);
				if (-1 == pos)
				{
					break;
				}
				value = xml.Substring(1, pos - 1);
			}
			else if ('\'' == xml[0]) // 开单引号
			{
				pos = xml.IndexOf('\'', 1); // 闭单引号
				if (-1 == pos)
				{
					break;
				}
				value = xml.Substring(1, pos - 1);
			}
			else if ('[' == xml[0])
			{
				pos = xml.IndexOf(']', 1);
				if (-1 == pos)
				{
					break;
				}
				value = xml.Substring(1, pos - 1);
			}
			else
			{
				pattern = @"\s";
				string[] values = Regex.Split(xml, pattern);
				if (1 < values.Count())
					value = values[0];
				else if (1 == values.Count())
				{
					int lastCloseChar = values[0].LastIndexOf(">");
					if ((values[0].Length - 1) == lastCloseChar) // 最后一个是>
					{
						value = values[0].Substring(0, values[0].Length - 1);
					}
					else
					{
						value = values[0].Substring(0, lastCloseChar);
					}
				}
				else
					value = "";

				pos = value.Length;
			}

			if (null == attributePairs)
			{
				attributePairs = new List<KeyValuePair<string, string>>();
			}
			attributePairs.Add(new KeyValuePair<string, string>(key, value));

			xml = xml.Substring(pos + 1).TrimStart();
			input = xml;
		} while ((xml != "") && (0 != xml.IndexOf(">")) && (0 != xml.IndexOf("/>")));

		return true;
	}



	public static bool IsXmlWithTagAndAttributeAndInnerTextClosed(string input, out string tagName, out List<KeyValuePair<string, string>> attributePairs, out string innerText) // 带标签,属性,innertext <abc x=y>...</abc>
	{
		tagName = null;
		attributePairs = null;
		innerText = null;

		int count0 = input.Count<char>(s => '<' == s);
		int pos = input.IndexOf("</");
		int count2 = input.Count<char>(s => '>' == s);
		int count3 = input.Count<char>(s => '=' == s);
		if ((2 != count0) || (0 >= pos) || (2 != count2) || (0 >= count3))
		{
			return false;
		}

		//string pattern = @"^<\w+\s+(\w+=(.+)?)+\s*>(?!(</)).*?</\w+>$"
		string pattern = @"^<\w+\s+(.+=.+)+\s*>(?!(</)).*?</\w+>$";
		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			string[] splitstr = Regex.Split(input, @"</.+>");
			if (2 != splitstr.Count())
			{
				return false;
			}

			string tagAttrsInner = splitstr[0];

			bool ret = SplitXmlTagAndAttribute(ref tagAttrsInner, ">", out tagName, out attributePairs);
			if (ret)
			{
				pos = tagAttrsInner.IndexOf(">");
				if (0 == pos)
				{
					innerText = tagAttrsInner.Substring(1); // 除>
				}
				else if (-1 == pos)
				{
					innerText = tagAttrsInner;
				}
			}

			return true;
		}

		return false;
	}

	public static bool IsXmlWithTagAndAttributeNotClosed(string input, out string tagName, out List<KeyValuePair<string, string>> attributePairs) // <abc m=n x="y">
	{
		tagName = null;
		attributePairs = null;

		int count0 = input.Count<char>(s => '<' == s);
		int count1 = input.IndexOf("</");
		int count2 = input.Count<char>(s => '>' == s);
		if ((2 == count0) && (0 < count1) && (2 == count2))
		{
			return false;
		}

		string pattern = @".*?/>$";
		Match match = Regex.Match(input, pattern);
		if (match.Success)
		{
			return false;
		}

		//string pattern = @"^<{1,1}/{0,0}(.+)?>{1,1}\B";
		//string pattern = @"^<\w+\s+(\w+=(.(?!(>.*</)))+)+\s*>$"
		pattern = @"^<\w+(\s+.*?=.*?)+\s*/{0,0}>$";

		Regex reg = new Regex(pattern);
		match = reg.Match(input);
		if (match.Success)
		{
			return SplitXmlTagAndAttribute(ref input, ">", out tagName, out attributePairs);
		}
		
		return false;
	}

	public static bool IsXmlSingleLineClosed(string input, out string tagName, out List<KeyValuePair<string, string>> attributePairs) // <abc x=y />
	{
		//string pattern = @"^(<{1,1}/{0,0}.*?/{1,1}>{1,1}){1,1}$";
		//string pattern = @"^<\w+(\s+.*?=.*?)*?\s*(/>){1,1}$";
		string pattern = @"^<\w+(\s+.+=.+)*?\s*/>$";

		tagName = null;
		attributePairs = null;

		int count0 = input.Count<char>(s => '<' == s);
		int pos = input.IndexOf("/>");
		int count2 = input.Count<char>(s => '>' == s);
		if ((2 == count0) || (0 >= pos) || (2 == count2))
		{
			return false;
		}

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			return SplitXmlTagAndAttribute(ref input, "/>", out tagName, out attributePairs);
		}

		return false;
	}

	/*
	 * <abc x=1>...
	 * 
	 */
	public static bool IsXmlWithTagAndAttributeAndInnerTextNotClosed(string input, out string tagName, out List<KeyValuePair<string, string>> attributePairs, out string innerText) // <abc x=1>...
	{
		tagName = null;
		attributePairs = null;
		innerText = null;
		
		//string pattern = @"^<\w*\s+(\w+\s*=\s*\S+)+>{1,1}(.*(?!(</)))?$";
		//string pattern = @"^<\w*\s+(\w+\s*=\s*\S+)+>\B.*?$";
		string pattern = @"^<\w+\s+(\w+=(.+)?)+\s*>(?!(</)).*?$";
		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			string[] splitstr = Regex.Split(input, @">");
			if (2 != splitstr.Count())
			{
				return false;
			}

			string tagAttrs = splitstr[0] + ">";

			bool ret = SplitXmlTagAndAttribute(ref tagAttrs, ">", out tagName, out attributePairs);
			if (!ret)
			{
				return false;
			}

			innerText = splitstr[1];
			return true;
		}

		return false;
	}

	public static bool IsXmlWithTagAndInnerTextNotClosed(string input, out string tagName, out string content) // <abc>...
	{
		//string pattern = @"^<\w*?>{1,1}(?!(</)).*?(?!>)$";
		string pattern = @"^<\w+>.*?$";

		tagName = null;
		content = null;

		int pos = input.IndexOf("</");
		if (0 <= pos)
		{
			return false;
		}

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			pos = input.IndexOf(">");
			tagName = input.Substring(1, pos - 1);
			content = input.Substring(pos + 1);
			return true;
		}

		return false;
	}

	public static bool IsXmlWithInnerTextOnly(string input, out string content)
	{
		string pattern = @"^(?!<).*?>{0,0}$";
		content = null;

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			content = input;
			return true;
		}

		return false;
	}

	public static bool IsXmlWithTagAndInnerTextColsed(string input, out string tagName, out string content) // <abc>...</abc>
	{
		//string pattern = @"^(<{1,1}/{0,0}\w*(?!=)>{1,1}.*?<{1,1}/{1,1}\w*>{1,1}){1,1}$";
		//string pattern = @"^<\w*(?!=)>{1,1}(?!(</)).*?</\w*>$";
		string pattern = @"^<\w+>{1,1}(?!(</)).*?</\w*>$";

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			int p_s = input.IndexOf("<");
			int p_e = input.IndexOf(">", p_s + 1);

			if ((-1 == p_s) || (-1 == p_e))
			{
				tagName = null;
				content = null;
				return false;
			}

			tagName = input.Substring(p_s + 1, p_e - p_s - 1);

			p_s = input.IndexOf("<", p_e + 1);
			if ((-1 == p_s) || (-1 == p_e))
			{
				tagName = null;
				content = null;
				return false;
			}

			content = input.Substring(p_e + 1, p_s - p_e - 1);
			return true;
		}

		tagName = null;
		content = null;
		return false;
	}

	public static bool IsXmlTagEnd(string input, out string tagName) // </abc>
	{
		//string pattern = @"^(</){1,1}\w*\b>{1,1}$";
		string pattern = @"^</\w+>$";

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			tagName = match.Value.Substring(2, match.Value.Length - 3).Trim();
			return true;
		}

		tagName = null;
		return false;
	}

	public static bool IsXmalComment(string input)
	{
		// <!--注释-->

		string pattern = @"^(<!--){1,1}.*?(-->){1,1}$";

		Regex reg = new Regex(pattern);
		Match match = reg.Match(input);
		if (match.Success)
		{
			return true;
		}
		return false;
	}

	public static void ClearXamlComment(ref string input)
	{
		string pattern = @"^(<!--){1,1}.*?(-->){1,1}$";
		Regex reg = new Regex(pattern);
		input = Regex.Replace(input, pattern, "");
	}
}



XML解析Json类:

class XmlNode
{
	public JsonValue JsonValue;
	public string Key;
	public int Depth;

	public XmlNode(int depth)
	{
		Depth = depth;
	}
}

public class XmlToJsonParser
{
	private const string Key_InnerText = "xml_inner_text";

	private string InnerText_LineBreak = "\r\n";

	private JsonObject mJson;
	private List<XmlNode> XmlNodes;
	private int Depth = -1;

	/*
	 * 强制如下格式所有...所对应的key为Key_InnerText
	 * 1. 
	 *     <abc>....
	 *  2.
	 *     <abc> ...</abc>
	 *  3.
	 *      <abc x=y>...</abc>
	 *  4.
	 *      <abc>...
	 *          ...
	 *      </abc>
	 */
	private bool ForceAllUseInnerText = false;

	public StdXmlToJsonParser()
	{
		mJson = new JsonObject();
		XmlNodes = new List<XmlNode>();

		XmlNode root = new XmlNode(++Depth);
		root.Key = "------------------------------ xml_2_json_root_key ------------------------------";
		root.JsonValue = mJson;

		XmlNodes.Add(root);
	}

	public string ToJson(bool pretty = false)
	{
		lock (XmlNodes)
		{
			string json = mJson.ToString(pretty);
			mJson.Clear();

#if DEBUG_PRINT
			Console.WriteLine(json);
#endif
			return json;
		}
	}

	public void SetInnerTextConnector(string connector)
	{
		InnerText_LineBreak = connector;
	}

	public void SetLocalLang(string local)
	{
		mJson.Add(CodePage.LocalLangKey, local);
	}

	public void AddKeyValuPair(string key, string value)
	{
		mJson.Add(key, value);
	}

	public void Parse(string line)
	{
		string tagName;
		string innerText;
		List<KeyValuePair<string, string>> attributes;

		if (line.Contains("<LabelInf value=[#0500694A#1201001B#050089EB#\\&x = 9#12010005#05008F1D#\\& = (50-9)/50*100 = 82%#12010005#0500693D#12010005#05001ABD#05006958#12010005]>"))
		{

		}

		if (TextUtil.IsXmlHeader(line))
		{
			return;
		}
		else if (TextUtil.IsXmalComment(line)) // 注释: <!-- adfaf -->
		{
			return;
		}
		else if (TextUtil.IsXmlWithTagAndInnerTextColsed(line, out tagName, out innerText)) // 带innertext的标签: <abc>...</abc>
		{
			ParseXmlWithTagAndInnerTextClosed(tagName, innerText);
		}
		else if (TextUtil.IsXmlSingleLineClosed(line, out tagName, out attributes)) // 单行闭合标签: <abc x=y />
		{
			ParseXmlWithSingleLineClosed(tagName, attributes);
		}
		else if (TextUtil.IsXmlTagStart(line, out tagName)) // 标签开始(无属性): <abc>
		{
			ParseXmlWithStartNoAttribute(tagName);
		}
		else if (TextUtil.IsXmlTagEnd(line, out tagName)) // 标签结束: </abc>
		{
			ParseXmlWithEnd(tagName);
		}
		else if (TextUtil.IsXmlWithTagAndAttributeNotClosed(line, out tagName, out attributes)) // 带属性的标签: <abc m=n x="y">
		{
			ParseXmlWithTagAndAttributeNotClosed(tagName, attributes);
		}
		/*
		 * 前置如下格式所有...所对应的key为Key_InnerText
		 * 
		 *     <abc x=y z=d>....</abc>
		 *     
		 */
		else if (TextUtil.IsXmlWithTagAndAttributeAndInnerTextClosed(line, out tagName, out attributes, out innerText)) // 带标签,属性,innertext <abc x=y>...</abc>
		{
			ParseXmlWithTagAndAttributesAndInnerTextClosed(tagName, attributes, innerText);
		}
		else if (TextUtil.IsXmlWithTagAndAttributeAndInnerTextNotClosed(line, out tagName, out attributes, out innerText)) // <abc x=1>...
		{
			ParseXmlWithTagAndAttributeAndInnerTextNotClose(tagName, attributes, innerText);
		}
		else if (TextUtil.IsXmlWithTagAndInnerTextNotClosed(line, out tagName, out innerText)) // 非闭合带内容标签: <abc>...
		{
			ParseXmlWithTagAndInnerTextNotClosed(tagName, innerText);
		}

		/*
		 *  <abc>
		 *      tag's content
		 *  </abc>
		 */
		else if (TextUtil.IsXmlWithInnerTextOnly(line, out innerText)) // innertext:
		{
			ParseXmlWithInnerTextOnly(innerText);
		}
		else
		{
			Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + line);
		}
	}

	private void ParseXmlWithTagAndAttributesAndInnerTextClosed(string tagName, List<KeyValuePair<string, string>> attributes, string innerText)
	{
		XmlNode node = new XmlNode(++Depth);
		node.JsonValue = new JsonObject();
		node.Key = tagName;

		foreach (KeyValuePair<string, string> kv in attributes)
		{
			node.JsonValue.AsJsonObject.Add(kv.Key, kv.Value);
		}

		node.JsonValue.AsJsonObject.Add(Key_InnerText, innerText);

		AddXmlNode(node, false);
	}

	private void ParseXmlWithTagAndAttributeAndInnerTextNotClose(string tagName, List<KeyValuePair<string, string>> attributes, string innerText)
	{
		XmlNode node = new XmlNode(++Depth);
		node.JsonValue = new JsonObject();
		node.Key = tagName;

		foreach (KeyValuePair<string, string> kv in attributes)
		{
			node.JsonValue.AsJsonObject.Add(kv.Key, kv.Value);
		}

		node.JsonValue.AsJsonObject.Add(Key_InnerText, innerText);

		AddXmlNode(node, true);
	}

	private void ParseXmlWithInnerTextOnly(string innerText)
	{
		lock (XmlNodes)
		{
			XmlNode lastNode = XmlNodes[XmlNodes.Count - 1];
			JsonValue jv = lastNode.JsonValue;
			if (jv.IsJsonObject)
			{
				XmlNode ppNode = GetParentNode(lastNode);
				if (ppNode.JsonValue.IsJsonObject)
				{
					jv = ppNode.JsonValue.AsJsonObject[lastNode.Key];
					ppNode.JsonValue.AsJsonObject.Remove(lastNode.Key);

					if (!jv.AsJsonObject.ContainsKey(Key_InnerText))
					{
						jv.AsJsonObject.Add(Key_InnerText, new JsonValue(innerText));
					}
					else
					{
						JsonValue innerJv = jv.AsJsonObject[Key_InnerText];
						jv.AsJsonObject.Remove(Key_InnerText);

						string contentNew = innerJv.AsString;
						contentNew += InnerText_LineBreak + innerText;

						jv.AsJsonObject.Add(Key_InnerText, contentNew);
					}
					ppNode.JsonValue.AsJsonObject.Add(lastNode.Key, jv);
				}
			}
			else if (jv.IsString)
			{
				XmlNode ppNode = GetParentNode(lastNode);
				ppNode.JsonValue.AsJsonObject.Remove(lastNode.Key);

				string contentNew = jv.AsString;
				contentNew += InnerText_LineBreak + innerText;
				ppNode.JsonValue.AsJsonObject.Add(lastNode.Key, contentNew);
			}
		}
	}

	private void ParseXmlWithTagAndInnerTextNotClosed(string tagName, string innerText)
	{
		XmlNode node = new XmlNode(++Depth);
		node.Key = tagName;

		if (ForceAllUseInnerText)
		{
			node.JsonValue = new JsonObject();
			node.JsonValue.AsJsonObject.Add(Key_InnerText, new JsonValue(innerText));
		}
		else
		{
			node.JsonValue = new JsonValue(innerText);
		}

		AddXmlNode(node, true);
	}
	
	private void ParseXmlWithTagAndInnerTextClosed(string tagName, string innerText)
	{
		XmlNode node = new XmlNode(++Depth);
		node.Key = tagName;
		if (ForceAllUseInnerText)
		{
			node.JsonValue = new JsonObject();
			node.JsonValue.AsJsonObject.Add(Key_InnerText, new JsonValue(innerText));
		}
		else
		{
			node.JsonValue = new JsonValue(innerText);
		}

		AddXmlNode(node, false);
	}

	private void ParseXmlWithSingleLineClosed(string tagName, List<KeyValuePair<string, string>> attributes)
	{
		XmlNode node = new XmlNode(++Depth);
		node.JsonValue = new JsonObject();
		node.Key = tagName;

		if (null != attributes && 0 < attributes.Count)
		{
			foreach (KeyValuePair<string, string> kv in attributes)
			{
				node.JsonValue.AsJsonObject.Add(kv.Key, kv.Value);
			}
		}

		AddXmlNode(node, false);
	}

	private void ParseXmlWithStartNoAttribute(string tagName)
	{
		XmlNode node = new XmlNode(++Depth);
		node.JsonValue = new JsonObject();
		node.Key = tagName;

		AddXmlNode(node, true);
	}

	private void ParseXmlWithEnd(string tagName)
	{
		lock (XmlNodes)
		{
			Depth--;
			XmlNode node = XmlNodes[XmlNodes.Count - 1];
			XmlNodes.RemoveAt(XmlNodes.Count - 1);
#if DEBUG_PRINT
			Console.WriteLine("Depth: " + Depth + "Pop node: " + node.Key);
#endif
		}
	}

	private void ParseXmlWithTagAndAttributeNotClosed(string tagName, List<KeyValuePair<string, string>> attributes)
	{
		XmlNode node = new XmlNode(++Depth);
		node.JsonValue = new JsonObject();
		node.Key = tagName;

		foreach (KeyValuePair<string, string> kv in attributes)
		{
			node.JsonValue.AsJsonObject.Add(kv.Key, kv.Value);
		}

		AddXmlNode(node, true);
	}

	private void AddXmlNode(XmlNode node, bool needPush)
	{
		lock (XmlNodes)
		{
			XmlNode parentNode = GetParentNode(node);
			if (!parentNode.JsonValue.AsJsonObject.ContainsKey(node.Key)) // 不包含当前节点相同的key
			{
				parentNode.JsonValue.AsJsonObject.Add(node.Key, node.JsonValue);
			}
			else // 包含当前节点相同的key
			{
				JsonValue existJV = parentNode.JsonValue.AsJsonObject[node.Key];

				if (existJV.IsJsonObject // 已包含的是对象
					|| existJV.IsString       // 或已包含对象是字符串
					)
				{
					parentNode.JsonValue.AsJsonObject.Remove(node.Key);

					JsonValue jarr = new JsonArray();
					jarr.AsJsonArray.Add(existJV);
					jarr.AsJsonArray.Add(node.JsonValue);

					parentNode.JsonValue.AsJsonObject.Add(node.Key, jarr);
				}
				else if (existJV.IsJsonArray) // 已包含的是数组
				{
					existJV.AsJsonArray.Add(node.JsonValue);
				}
				else // 错误
				{
					Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Error xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
				}
			}

			if (needPush)
			{
				XmlNodes.Add(node);
#if DEBUG_PRINT
				Console.WriteLine("Depth: " + Depth + "Push node: " + node.Key);
#endif
			}
			else
			{
				Depth--;
			}
		}
	}

	private XmlNode GetParentNode(XmlNode node)
	{
		int lastIdx = XmlNodes.Count - 1;

		for (int i = lastIdx; i >= 0; i--)
		{
			XmlNode pnd = XmlNodes[i];
			if ((pnd.Depth + 1) == node.Depth)
			{
				return pnd;
			}
		}

		return null;
	}

	private JsonValue IsHasTheSameNode(XmlNode node)
	{
		XmlNode parentNode = GetParentNode(node);
		JsonValue parentJv;

		if (null != parentNode)
		{
			parentJv = parentNode.JsonValue;
			if (parentJv.IsJsonObject)
			{
				if (parentJv.AsJsonObject.ContainsKey(node.Key))
				{
					return parentJv;
				}
			}
			else
			{
				return parentJv;
			}
		}

		return JsonValue.Null;
	}
}




使用:

FileStream fstream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read);

using (StreamReader sreader = new StreamReader(fstream, encoding))
{
    string line;

    while (!sreader.EndOfStream)
    {
        line = sreader.ReadLine();
        line = line.Trim();
        if (string.IsNullOrEmpty(line))
        {
            continue;
        }

        xmlToJsonParser.Parse(line); // 一行一行解析
    }
}
fstream.Close();

string json = xmlToJsonParser.ToJson(true);// 得到Json字符串


SpringBoot项目里调用老旧C# WebService接口,我是怎么用HttpClientBuilder一步步搞定的(附XML转JSON完整代码) 本文详细介绍了在SpringBoot项目中如何通过HttpClientBuilder手动构建SOAP请求,实现与老旧C# WebService接口的集成。内容包括XML请求构造、命名空间处理、XML到JSON转换的完整代码实现,以及性能优化和异常处理的最佳实践,为开发者提供了一套可靠的解决方案。 阅读详情

相关推荐

C# XML与Json之间相互转换

在C#开发中,经常会涉及到将数据在XML和JSON之间进行转换的需求。XML和JSON是两种常用的数据交换格式,XML具有良好的可读性和结构化特性,而JSON则更加紧凑和易于解析。本文将介绍如何使用C#实现XML与JSON之间的相互转换,并提供相应的源代码示例。首先,我们需要使用C#的内置库来解析XML数据并将其转换为JSON格式。在.NET Framework和.NET Core中,可以使用命名空间中的类来处理XML数据。以下是一个示例代码,演示了如何将XML转换为JSON: 在上述代码中,我们首先创建一

XtmData的博客 1140

C#将xml转成json

【代码】C#将xml转成json。

Leckun的专栏 724

解锁C#中的数据转换魔法:XML与JSON的无缝对接

通过上述内容的学习,你应该对如何在C#中进行XML与JSON之间的转换有了深刻的理解。无论是在构建RESTful API、处理配置文件还是与其他系统进行数据交换时,掌握这些技巧都将极大地提升你的工作效率。希望这篇文章能激发你的灵感,并为你的项目带来实际的帮助。

墨夶的博客 1062

使用C#将XML转化为JSON

使用C#将XML转化为JSON C#中有专门用于XML转化到JSON的库,Newtonsoft.Json。 官方文档地址:https://www.newtonsoft.com/json/help/html/Introduction.htm 先写一个类来专门做XML解析:(ps.别忘了using Newtonsoft.Json,如果报错去NuGet Package Manager搜一下然后安装...

Sophie1797的博客 7514

手把手教你搭建Howland电流源:从原理图到实测避坑指南(附Python数据分析)

本文详细介绍了Howland电流源的设计与实现,从原理图到实测避坑指南,涵盖电阻匹配、运放选择和PCB布局等关键环节。通过Python数据分析,展示了如何优化电路性能并解决常见问题,适合电子工程师和爱好者参考。

weixin_29291069的博客 644

全志T113-S3 Linux系统移植实战:从硬件配置到内核启动全解析

本文详细解析了将Linux系统移植到全志T113-S3嵌入式芯片的完整实战流程。内容涵盖从开发环境搭建、Longan SDK源码获取,到关键的U-Boot配置、DDR初始化、Linux内核编译与设备树定制,以及根文件系统构建与启动脚本分析。文章结合硬件配置与启动日志解读,提供了从硬件配置到内核启动的全方位指导,帮助开发者高效完成系统移植。

ik67890123的博客 526

C# json 转 xml 字符串

本文告诉大家如何将 json 转 xml 或将 xml 转 json 字符串

lindexi 5636

Python实战:ERA5风场数据区域提取与风向合成可视化全流程解析

本文详细解析了使用Python处理ERA5风场数据的完整流程,包括NC文件读取、特定区域数据提取、u/v分量合成风向风速的计算,以及利用Matplotlib进行风场时空演变可视化。内容涵盖从环境搭建、数据获取到高级绘图与性能优化的实战经验,为气象数据分析、风能评估及气候研究提供了一套清晰、可操作的技术指南。

swift5iosmith的博客 311

c# XML转JSON、JSON转XML,object转JSON

public static string XmlTojson(this string s, string r = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") { s = s.Replace(r, ""); var doc = new XmlDocument(); ...

Qin066的博客 5万+

【ARM Trace32(劳特巴赫) 高级篇 20 -- SNOOPer 使用介绍】

在 Lauterbach TRACE32 调试系统中,Snooper是一种特殊的监视工具,它能够在不中断处理器执行的情况下监视和记录特定内存地址的数据变化。这对于系统级调试、性能分析、数据流监视以及实时系统的问题追踪特别有用,尤其是在无法使用中断的情况下。当你设置了一个或多个Snooper时,TRACE32 硬件将不断地监视指定的内存地址,一旦发生了读写操作,就会将相关信息记录下来。这样你就可以看到某个地址的数据是什么时候以及如何被修改的,而不会影响目标系统的运行。

CodingCos的博客 2779

【重识云原生】第四章云网络4.9.5.1节下一代智能网卡——DPU综述

随着数据中心的高速发展,通信能力和计算能力成为数据中心基础设施的相辅相成的两个重要发展方向。若数据中心仅关注计算能力的提升,通信基础设施的提升跟不上,那么数据中心的整体系统性能依然受限,无法发挥出真正的潜力。DPU的提出背景就是应对这些数据量和复杂性的指数级增长。未来,需要将计算移至接近数据的位置,这是目前业界所公认的以数据为中心的体系结构下的创新。综上,DPU对数据中心来说,是通过更明细的分工来实现效率的提升、实现总体系统的成本最优化。...

junbaozi的专栏 1729

c#动态类转json,再由json转xml

直接上代码了,多说无意了。 using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.Runtime.CompilerServices; using Ne...

weixin_30364325的博客 125

STM32外部中断EXTI原理与飞控实时应用实战

外部中断(EXTI)是嵌入式系统中实现事件驱动和实时响应的核心机制,其本质是将外部电平变化转化为可调度的CPU中断事件。基于ARM Cortex-M NVIC架构,EXTI通过GPIO-EXTI-NVIC三级硬件通路实现低延迟信号捕获,具备边沿触发、优先级管理与挂起控制等关键能力。在四轴飞控、工业传感器、人机交互等对毫秒级响应有强需求的场景中,EXTI显著优于轮询方式,兼顾实时性与CPU资源效率。实际开发需严格遵循SYSCFG映射→EXTI配置→NVIC使能的时序逻辑,并规避常见陷阱如中断号误配、伪触发、低

weixin_36382073的博客 69

C# xml转json(xml、json相互转换)

[HttpGet] public IHttpActionResult XMLToJSON( ) { var xml = @"<?xml version=""1.0"" encoding=""utf -8""?>" + "<ArrayOfString>" + "<string>广东 深圳</string><string>今日...

qq_32911691的博客 2701

功能安全实战系列12-英飞凌TC3xx锁步核及其自检开发

本文介绍了英飞凌Tricore系列芯片的锁步核(Lockstep Core)功能及其故障注入自检机制。锁步核通过主核和检查核同步执行指令,并比较输出结果来检测硬件故障。文章详细阐述了锁步核的工作原理、使能配置方法以及故障注入自检的实现过程。故障注入测试通过专用寄存器LCLTEST触发,系统会定期自动测试比较器节点,验证锁步核的故障检测能力。当检测到异常时,会触发SMU模块的警报机制。该技术为汽车电子系统提供了重要的功能安全保障。

initiallizer的博客 930

一种独特机理驱动的化学反应分类器详解

代码位置第 47-300+ 行// atom_494: 硫原子,度数=2,化合价=2,无H,无电荷!// atom_35: 氧原子,度数=1,1个H,无电荷// atom_347: 氧原子,度数=2,无H,无电荷!→atom_494()[OD1h1+0]→atom_35()→atom_347()特性传统方法(MCS)NameRXN(机理驱动)匹配策略最大公共子结构原子类型模式 + 操作码时间复杂度O(n) - 线性扫描机理理解无内置化学机理原子映射需额外计算自动推导准确性结构相似。

ASKCOS博客 164

xml转json c语言,c#动态类转json,再由json转xml

直接上代码了,多说无意了。using System;using System.Collections;using System.Collections.Generic;using System.ComponentModel;using System.Dynamic;using System.Runtime.CompilerServices;using Newtonsoft.Json;using S...

weixin_39901358的博客 192

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

C# XML转JSON

XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlData.ToString()); string jsonText = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc); 转载于:https://www.cnblogs.c...

weixin_30369041的博客 133

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

【转】C# Json数据转换为Xml

直接上代码:public static XmlDocument JsonToXml(string joson) { JavaScriptSerializer oSerializer = new JavaScriptSerializer(); Dictionary<string, object> Dic = (Dictionary<str

一无所有 1901

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

c# 多属性json 转 xml

c# 多属性json 转 xml 支持多节点json转换为xml

Simon1003的博客 707

C# json转xml

直接上code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using Newtonsoft.Json; namespace JsonToXml { class Program { ...

weixin_30556959的博客 218

c语言json转xml,C# XML与Json之间相互转换实例详解

对于这转换其实很简单,其中最重要的就是先要引用类库。可以到官网进行下载引用http://json.codeplex.com。XML转换为Json字符串复制代码 代码如下:string xml = @"Alanhttp://www.jb51.netLouishttp://www.jb51.net";这是在代码中预定义的一个xml字符串。复制代码 代码如下:mlDocument doc = new X...

weixin_39945816的博客 397

C#之json字符串转xml字符串

为什么80%的码农都做不了架构师?>>> ...

weixin_34270606的博客 659

C#中json转为xml源码(转)

第一种写法: XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max); XmlDocument doc = new XmlDocument(); doc.Load(reader);

CCwm0129的专栏 1302

c# json字符串转xml对象代码

XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max); XmlDocument doc = new XmlDocument(); doc.Load(reader); 收藏一下吧 以后万

hxkjnet360的专栏 932

C#对XML、JSON等格式的解析 (转)

C#对XML、JSON等格式的解析 一、C#对XML格式数据的解析 1、用XMLDocument来解析 XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("test.xml"); //创建新节点 XmlElement nn = xmlDocument.CreateElement("...

weixin_30355437的博客 190
上一篇: WPF进程接收启动参数
下一篇: C++字符串剔除首尾不可见字符
OneOnce
博客等级 码龄17年 67粉丝 43原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OneOnce

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值