c# 用action做参数进行封装操作

本文介绍了一种生成XML文档的方法,通过定义一个通用的创建XML文档的函数,并结合具体需求来填充XML的内容。同时,还提供了一个将XML文档转换为字符串的实用函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:有一批xml字符串要生成,xml的结构格式是一样的,内容不一样,需要一个方法来生成结构,不同的内容用不同的方法单独写。

封装方法:

 private static XmlDocument createDoc(Action<XmlDocument, XmlNode> func, string comment, string id)
        {
            XmlDocument doc = new XmlDocument();
            XmlNode node = doc.CreateXmlDeclaration("1.0", "gbk", null);
            doc.AppendChild(node);

            XmlNode businessNode = doc.CreateElement("business");
            XmlAttribute commentAttr = doc.CreateAttribute("comment");
            commentAttr.Value = comment;
            XmlAttribute idAttr = doc.CreateAttribute("id");
            idAttr.Value = id;
            businessNode.Attributes.Append(commentAttr);
            businessNode.Attributes.Append(idAttr);

            XmlNode body = doc.CreateElement("body");
            XmlAttribute lxdmAttr = doc.CreateAttribute("yylxdm");
            lxdmAttr.Value = "1";
            body.Attributes.Append(lxdmAttr);
            XmlNode input = doc.CreateElement("input");

            func(doc, input);

            body.AppendChild(input);
            businessNode.AppendChild(body);

            doc.AppendChild(businessNode);
            return doc;
        }

使用:

 public static void Zcmxxdr()
        {
            XmlDocument xmldoc = createDoc((XmlDocument doc, XmlNode input) =>
            {
                XmlNode zcmxxNode = doc.CreateElement("zcmxx");
                zcmxxNode.InnerText = skpInfo.ZhuCeMa;
                input.AppendChild(zcmxxNode);
            }, "注册码信息导入", "ZCMDR");

            string str = xmlToString(xmldoc);

            System.Diagnostics.Debug.WriteLine(str);
        }

xml转字符串(全格式,不丢内容):

  private static string xmlToString(XmlDocument doc)
        {
            string tmpdir = "tmp";
            if (!Directory.Exists(tmpdir))
            {
                Directory.CreateDirectory(tmpdir);
            }
            string tmpfile = string.Format("{0}/{1}.xml", tmpdir, Guid.NewGuid());
            doc.Save(tmpfile);

            using (StreamReader sr = new StreamReader(tmpfile, System.Text.Encoding.GetEncoding("gbk")))
            {
                string xmlString = sr.ReadToEnd();
                return xmlString;
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值