需求:有一批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;
}
}