jsonToXML XMLTojson
乐修远
2023-12-01
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Json;
using System.Collections;
//using Open_Newtonsoft_Json;
namespace WeChatTool
{
public static class xmlHelper
{
//XmlTextWriter
public static void ss()
{
String filename = String.Concat("test3.xml");
using (StreamWriter sw = new StreamWriter(filename))
{
// Create Xml Writer.
XmlTextWriter xmlWriter = new XmlTextWriter(sw);
// 也可以使用public XmlTextWriter(string filename, Encoding encoding)来构造
// encoding默认为 UTF-8.
//XmlTextWriter writer = new XmlTextWriter("test3.xml", null);
// Set indenting so that its easier to read XML when open in Notepad and such apps.
xmlWriter.Formatting = Formatting.Indented;
// This will output the XML declaration
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Contacts");
xmlWriter.WriteStartElement("Contact");
xmlWriter.WriteAttributeString("id", "01");
xmlWriter.WriteElementString("Name", "Daisy Abbey");
xmlWriter.WriteElementString("Gender", "female");
// close contact </contact>
xmlWriter.WriteEndElement();
// close contacts </contact>
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
}
//LINQ to XML 的XDocument
public static void xx()
{
//var doc = new XDocument(new XElement("Contacts",
// new XElement("Contact", new XAttribute("id", "01"),
// new XElement("Name", "Daisy Abbey"),
// new XElement("Gender", "female"))));
//doc.Save("test2.xml");
}
//XmlDocument 写入
public static void XmlDocumentWriter(string userName, string appid, string appsecret, DateTime appdate)
{
#region MyRegion
try
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
//if (File.Exists(xmlPath)==false string.IsNullOrEmpty(xmlPath) || xmlPath == "")
if (File.Exists(xmlPath) == false)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
var root = xmlDoc.CreateElement("config");
xmlDoc.AppendChild(root);
// User UserInfo
XmlElement elementUser = xmlDoc.CreateElement("dev");
//elementUser.InnerText = userName;
root.AppendChild(elementUser);
XmlElement elementName = xmlDoc.CreateElement("Name");
elementName.InnerText = userName;
elementUser.AppendChild(elementName);
XmlElement elementAppid = xmlDoc.CreateElement("Appid");
elementAppid.InnerText = appid;
//XmlAttribute attrID = xmlDoc.CreateAttribute("id");
//attrID.Value = "01";
//elementAppid.Attributes.Append(attrID);
elementUser.AppendChild(elementAppid);
XmlElement elementAppsecret = xmlDoc.CreateElement("Appsecret");
elementAppsecret.InnerText = appsecret;
elementUser.AppendChild(elementAppsecret);
//XmlElement elementDate = xmlDoc.CreateElement("AppDate");
//elementDate.InnerText = appdate.ToLocalTime().ToString();
//elementUser.AppendChild(elementDate);
xmlDoc.Save("config.xml");
MessageBox.Show("用户信息保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
//XmlNode node = doc.SelectSingleNode("/Users/UserInfo/Name");
XmlNodeList nodes = xmlDoc.SelectNodes("/config/dev");
if (nodes.Count > 0)
{
// User
XmlNode root = xmlDoc.SelectSingleNode("/config");
XmlElement elementUser = xmlDoc.CreateElement("dev");
//elementUser.InnerText = userName;
root.AppendChild(elementUser);
XmlElement elementName = xmlDoc.CreateElement("Name");
elementName.InnerText = userName;
elementUser.AppendChild(elementName);
XmlElement elementAppid = xmlDoc.CreateElement("Appid");
elementAppid.InnerText = appid;
//XmlAttribute attrID = xmlDoc.CreateAttribute("id");
//attrID.Value = "01";
//elementAppid.Attributes.Append(attrID);
elementUser.AppendChild(elementAppid);
XmlElement elementAppsecret = xmlDoc.CreateElement("Appsecret");
elementAppsecret.InnerText = appsecret;
elementUser.AppendChild(elementAppsecret);
//XmlElement elementDate = xmlDoc.CreateElement("AppDate");
//elementDate.InnerText = appdate.ToLocalTime().ToString();
//elementUser.AppendChild(elementDate);
xmlDoc.Save("config.xml");
MessageBox.Show("用户信息保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show("用户信息保存有问题! " + ex.ToString(), "提示信息!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
//throw;
}
#endregion
}
//XmlDocument11 读取
public static Queue XmlDocumentQuery()
{
Queue queue = new Queue();
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
if (string.IsNullOrWhiteSpace(xmlPath) || xmlPath == null)
{
return queue;
}
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
XmlNodeList nodes = doc.SelectNodes("/config/dev");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
if (xmlnode.ChildNodes.Count > 2)
{
FrmUser user = new FrmUser();
user.UserName = xmlnode.ChildNodes[0].InnerText;
user.Appid = xmlnode.ChildNodes[1].InnerText;
user.Appsecret = xmlnode.ChildNodes[2].InnerText;
queue.Enqueue(user);
}
else if (xmlnode.ChildNodes.Count > 1)
{
FrmUser user = new FrmUser();
user.UserName = xmlnode.ChildNodes[0].InnerText;
user.Appid = xmlnode.ChildNodes[1].InnerText;
//user.Appsecret = xmlnode.ChildNodes[2].InnerText;
queue.Enqueue(user);
}
else if (xmlnode.ChildNodes.Count > 0)
{
FrmUser user = new FrmUser();
user.UserName = xmlnode.ChildNodes[0].InnerText;
//user.Appid = xmlnode.ChildNodes[1].InnerText;
//user.Appsecret = xmlnode.ChildNodes[2].InnerText;
queue.Enqueue(user);
}
}
}
return queue;
}
//XmlDocument 读取
public static XmlNode XmlDocumentQuery(string userName, string appid, string appsecret, DateTime appdate)
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "UserInfo.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
string xx = userName;
DateTime xx1 = appdate;
//XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
XmlNodeList nodes = doc.SelectNodes("/Users/UserInfo");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
foreach (XmlNode xmlSubNode in xmlnode.ChildNodes)
{
if (xmlSubNode.InnerText == xx)
{
//this.richTextBox3.AppendText("用户信息:");
foreach (XmlNode SubNode in xmlnode.ChildNodes)
{
return SubNode;
//this.richTextBox3.AppendText(Environment.NewLine + " " + SubNode.Name + ":" + SubNode.InnerText);
}
//return;
}
}
}
}
return null;
}
//XmlDocument 修改
public static void XmlDocumentModified(FrmUser oldUser, FrmUser newuUser, DateTime appdate)
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
//XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
XmlNodeList nodes = doc.SelectNodes("/config/dev");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
if (xmlnode.ChildNodes.Count > 2)
{
if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName
&& xmlnode.ChildNodes[1].InnerText == oldUser.Appid
&& xmlnode.ChildNodes[2].InnerText == oldUser.Appsecret)
{
xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
xmlnode.ChildNodes[1].InnerText = newuUser.Appid;
xmlnode.ChildNodes[2].InnerText = newuUser.Appsecret;
}
}
else if (xmlnode.ChildNodes.Count > 1)
{
if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName
&& xmlnode.ChildNodes[1].InnerText == oldUser.Appid)
{
xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
xmlnode.ChildNodes[1].InnerText = newuUser.Appid;
}
}
else if (xmlnode.ChildNodes.Count > 0)
{
if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName)
{
xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
}
}
}
}
doc.Save("config.xml");
MessageBox.Show("用户信息修改保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//XmlDocument 删除
public static void XmlDocumentDelete(FrmUser user, DateTime appdate)
{
string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
//根据要查询的字段进行查询,遍历使用的是xpath
//XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
XmlNodeList nodes = doc.SelectNodes("/config/dev");
foreach (XmlNode xmlnode in nodes)
{
if (xmlnode.HasChildNodes)
{
if (xmlnode.ChildNodes.Count > 2)
{
if (xmlnode.ChildNodes[0].InnerText == user.UserName
&& xmlnode.ChildNodes[1].InnerText == user.Appid
&& xmlnode.ChildNodes[2].InnerText == user.Appsecret)
{
XmlNode parentNode = xmlnode.ParentNode;
parentNode.RemoveChild(xmlnode);
}
}
else if (xmlnode.ChildNodes.Count > 1)
{
if (xmlnode.ChildNodes[0].InnerText == user.UserName
&& xmlnode.ChildNodes[1].InnerText == user.Appid)
{
XmlNode parentNode = xmlnode.ParentNode;
parentNode.RemoveChild(xmlnode);
}
}
else if (xmlnode.ChildNodes.Count > 0)
{
if (xmlnode.ChildNodes[0].InnerText == user.UserName)
{
XmlNode parentNode = xmlnode.ParentNode;
parentNode.RemoveChild(xmlnode);
}
}
}
}
doc.Save("config.xml");
MessageBox.Show("用户信息删除保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public static XmlDocument JsonToXml(string json)
{
XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
return doc;
}
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
string json = null;
//StringBuilder sb = new StringBuilder();
//JsonSerializer serialize = new JsonSerializer();
//serialize.Serialize
DataContractJsonSerializer serialize = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serialize.WriteObject(ms, obj);
byte[] readbyte = new byte[ms.Length];
ms.Read(readbyte, 0, (int)ms.Length);
json = Encoding.UTF8.GetString(readbyte);
return json;
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString, object obj)
{
//System.Runtime.Serialization.Json.DataContractJsonSerializer
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}
//从一个对象信息生成Json串
public static string WebObjectToJson(object obj)
{
//System.Web.Extensions
//System.Web.Script.Serialization.JavaScriptSerializer
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
serializer.Serialize(obj, sb);
return sb.ToString();
}
// 从一个Json串生成对象信息
public static object WebJsonToObject(string jsonString, object obj)
{
//System.Web.Extensions
//System.Web.Script.Serialization.JavaScriptSerializer
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
return serializer.Deserialize(jsonString, obj.GetType());
}
}
}