winform,xml读取与写入
阅读原文时间:2023年07月09日阅读:3

创建两个xml文件,一个 xml做为模板配置项,另一个做为临时接收数据。

private static string localPath = System.Environment.CurrentDirectory + @"\test\";

private static string localPathOld = System.Environment.CurrentDirectory + @"\test\YUYUE_PRINTOld.xml"; private static string localPathAdd = System.Environment.CurrentDirectory + @"\test\YUYUE_PRINT.xml";

写入方法:

string path = localPath + "/YUYUE_PRINTOld.xml";

string stu_At= "{'name': '0000899112','BarcodeRecognition': 'UPC-E','Sex': '男','Age': '27','Blood': '全血','BarCode': '210720002147','Content': '网织红细胞计数','iMode': 0}";
var docment = CustomerFormBase.Json2Xml(stu_At);
docment.Save(path);

xml读取方法:

///

/// xml读取 ///
///
///
private void button2_Click(object sender, EventArgs e)
{
string path = localPath + "/YUYUE_PRINTOld.xml";

        string stu\_At = "{\\"name\\":\\"0000899112 宁强\\",\\"BarcodeRecognition\\": \\"UPC-E\\",\\"Sex\\":\\"男\\",\\"Age\\": \\"27\\",\\"Blood\\": \\"全血\\",\\"BarCode\\": \\"210720002147\\",\\"Content\\": \\"网织红细胞计数\\",\\"iMode\\": 0}";  
        var docment = CustomerFormBase.Json2Xml(stu\_At);  
        docment.Save(path);

        StringBuilder m\_sbData = new StringBuilder("");  
        var xmlTemporary = CustomerFormBase.XmlTemporaryFiles(localPathOld);  
        var xmlConfigurationF = CustomerFormBase.XmlConfigurationFile(localPathAdd);  
        bool isXml = true;  
        if (xmlTemporary==null)  
        {  
            isXml = false;  
            MessageBox.Show("xml临时文件读取失败,请查看文件是text文件夹,以及对应文件是否存在!");  
        }  
        if (xmlConfigurationF==null)  
        {  
            isXml = false;  
            MessageBox.Show("xml配置文件读取失败,请查看文件是text文件夹,以及对应文件是否存在!");  
        }  
        List<XmlOld> xmlData = new List<XmlOld>();  
        if (isXml)  
        {  
            bool isXmlModel = true;  
            foreach (DataRow drXML in xmlConfigurationF.Rows)  
            {  
                var xmlModel = new XmlOld();  
                if (decimal.TryParse(drXML\["X"\].ToString(), out decimal xAt))  
                {  
                    xmlModel.X = xAt;  
                }  
                else  
                {  
                    isXmlModel = false;  
                }  
                if (decimal.TryParse(drXML\["Y"\].ToString(), out decimal yAt))  
                {  
                    xmlModel.Y = yAt;  
                }  
                else  
                {  
                    isXmlModel = false;  
                }  
                if (!string.IsNullOrWhiteSpace(drXML\["Names"\].ToString()))  
                {  
                    xmlModel.Names = drXML\["Names"\].ToString();  
                    xmlModel.NameInfo = xmlTemporary.GetValueByXmlNodeName(xmlModel.Names.Trim());  
                }  
                else  
                {  
                    isXmlModel = false;  
                }  
                if (isXmlModel)  
                {  
                    xmlData.Add(xmlModel);  
                }  
                else  
                {  
                    MessageBox.Show("X/Y/Names都为必填项不可为空,并且X/Y只能位数字");  
                    break;  
                }  
                SetPagedirection(0);//设置页模式打印方向  
                SetPagestartposition(Convert.ToInt32(xmlModel.X), Convert.ToInt32(xmlModel.Y));//设置页模式数据打印起始位置  
                m\_sbData = new StringBuilder(xmlModel.NameInfo);//性别  
                PrintString(m\_sbData, 0);//打印字符串  
            }  
            if (isXmlModel)  
            {  
                this.txt\_Xml.Text = "读取成功";  
            }  
            else  
            {  
                this.txt\_Xml.Text = "读取失败";  
            }  
        }  
    }

 创建一个CustomerFormBase类

public abstract class CustomerFormBase
{
[JsonIgnore]
public string ExtendData { get; set; }
public static T Parse(string v) where T : CustomerFormBase
{
var value = JsonConvert.DeserializeObject(v);

        var xml = JsonConvert.DeserializeXmlNode(v, "root");  
        value.ExtendData = xml.OuterXml;

        return value;  
    }

    public static List<T> ParseToList<T>(string vs) where T : CustomerFormBase  
    {  
        var values = new List<T>();  
        var valueStrs = JsonConvert.DeserializeObject<List<string>>(vs);  
        foreach (var valueStr in valueStrs)  
        {  
            values.Add(Parse<T>(valueStr));  
        }

        return values;

    }

    public virtual JObject ToMergedObject()  
    {  
        var json = "{}";

        if (!string.IsNullOrWhiteSpace(ExtendData))  
        {  
            var doc = new XmlDocument();  
            doc.LoadXml(ExtendData);

            json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);  
        }

        var obj = JObject.Parse(json);  
        var norObj = JObject.FromObject(this);

        obj.Merge(norObj);  
        obj.Remove(nameof(ExtendData));

        return obj;  
    }

    public override string ToString()  
    {  
        return ToMergedObject().ToString();  
    }

    /// <summary>  
    /// 根据xml节点获取对应的数据  
    /// </summary>  
    /// <param name="xmlNodeName">xml节点名称</param>  
    /// <returns></returns>  
    public string GetValueByXmlNodeName(string xmlNodeName)  
    {  
        var jObject = ToMergedObject();  
        var tokenValue = jObject.SelectToken(xmlNodeName);  
        if (tokenValue != null)  
        {  
            if (tokenValue.Type == JTokenType.Array)  
            {  
                var arrayValue = tokenValue.Value<JArray>().Children();  
                return string.Join("|", arrayValue);  
            }  
            else  
            {  
                return tokenValue.Value<string>();  
            }  
        }  
        else  
        {  
            return string.Empty;  
        }  
    }

    /// <summary>  
    /// 更新extendData的值  
    /// </summary>  
    /// <param name="keyValues"></param>  
    /// <returns></returns>  
    public bool addOrUpdateNodeValue<T>(Dictionary<string, string> keyValues) where T : CustomerFormBase  
    {  
        var jObject = ToMergedObject();

        foreach (var key in keyValues.Keys)  
        {  
            var jToken = jObject.SelectToken(key);  
            if (jToken == null)  
            {  
                jObject.Add(key, keyValues\[key\]);  
            }  
            else  
            {  
                jObject\[key\] = keyValues\[key\];  
            }  
        }

        this.ExtendData = Parse<T>(jObject.ToString()).ExtendData;

        return true;  
    }

    /// <summary>  
    /// json字符串转换为Xml对象  
    /// </summary>  
    /// <param name="sJson"></param>  
    /// <returns></returns>  
    public static XmlDocument Json2Xml(string sJson)  
    {  
        JavaScriptSerializer oSerializer = new JavaScriptSerializer();  
        Dictionary<string, object> Dic = (Dictionary<string, object>)oSerializer.DeserializeObject(sJson);  
        XmlDocument doc = new XmlDocument();  
        XmlDeclaration xmlDec;  
        xmlDec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);  
        doc.InsertBefore(xmlDec, doc.DocumentElement);  
        XmlElement nRoot = doc.CreateElement("root");  
        doc.AppendChild(nRoot);  
        foreach (KeyValuePair<string, object> item in Dic)  
        {  
            XmlElement element = doc.CreateElement(item.Key);  
            KeyValue2Xml(element, item);  
            nRoot.AppendChild(element);  
        }  
        return doc;  
    }

    public static void KeyValue2Xml(XmlElement node, KeyValuePair<string, object> Source)  
    {  
        object kValue = Source.Value;  
        if (kValue.GetType() == typeof(Dictionary<string, object>))  
        {  
            foreach (KeyValuePair<string, object> item in kValue as Dictionary<string, object>)  
            {  
                XmlElement element = node.OwnerDocument.CreateElement(item.Key);  
                KeyValue2Xml(element, item);  
                node.AppendChild(element);  
            }  
        }  
        else if (kValue.GetType() == typeof(object\[\]))  
        {  
            object\[\] o = kValue as object\[\];  
            for (int i = 0; i < o.Length; i++)  
            {  
                XmlElement xitem = node.OwnerDocument.CreateElement("Item");  
                KeyValuePair<string, object> item = new KeyValuePair<string, object>("Item", o);  
                KeyValue2Xml(xitem, item);  
                node.AppendChild(xitem);  
            }

        }  
        else  
        {  
            XmlText text = node.OwnerDocument.CreateTextNode(kValue.ToString());  
            node.AppendChild(text);  
        }  
    }

    /// <summary>  
    /// xml临时文件读取  
    /// </summary>  
    public static XmlOld XmlTemporaryFiles(string localPathOld)  
    {  
        if (!File.Exists(localPathOld))  
        {  
            return null;  
        }  
        else  
        {  
            var xmlModel = new XmlOld();  
            XmlDocument xmlDoc = new XmlDocument();  
            xmlDoc.Load(localPathOld);//读取xml文件  
            XmlNode xn = xmlDoc.SelectSingleNode("root");  
            var xmlText = xn.InnerXml.ToString();  
            if (xmlText.Length > 0)  
            {  
                xmlText = "<root>" + xmlText + "</root>";  
                xmlModel.ExtendData = xmlText;  
                return xmlModel;  
            }  
            else  
            {  
                return null;  
            }  
        }  
    }

    /// <summary>  
    /// xml配置文件读取  
    /// </summary>  
    public static DataTable XmlConfigurationFile(string localPathAdd)  
    {  
        if (!File.Exists(localPathAdd))//若文件夹不存在则新建文件夹  
        {  
            return null;  
        }  
        else  
        {  
            DataSet ds = new DataSet();  
            ds.ReadXml(localPathAdd);  
            var xmlSet = ds.Tables\["Line"\];  
            if (xmlSet != null)  
            {  
                return xmlSet;  
            }  
            else  
            {  
                return null;  
            }  
        }  
    }  
}

创建XmlOld类:

///

/// xml信息字段接收 ///
public partial class XmlOld: CustomerFormBase
{
/// /// X抽 ///
public decimal X { get; set; }
/// /// Y抽 ///
public decimal Y { get; set; }
/// /// 字段名称 ///
public string Names { get; set; }
}