C#操作xml方法1

using System.Xml.Linq;

static class xmlOp1
{
  /// <summary>
  /// 读操作
  /// </summary>
  /// <param name="path"></param>
  /// <param name="m_tPara"></param>
  public static void readXmlPara(string path, ref syspara m_tPara)
  {
  //加载XML文件
  XDocument myXDoc = XDocument.Load(path);
  //获取XML文件根节点
  XElement rootNode = myXDoc.Root;
  //获取根节点下面对应的值
  XElement childNode0 = rootNode.Element("通过");
  XElement childNode1 = rootNode.Element("不通过");
  XElement childNode2 = rootNode.Element("执行");
  XElement childNode3 = rootNode.Element("测试报告路径");
  //赋值给结构体变量
  m_tPara.pass = long.Parse(childNode0.Value);
  m_tPara.fail = long.Parse(childNode1.Value);
  m_tPara.testing = long.Parse(childNode2.Value);
  m_tPara.testDataPath = childNode3.Value;
  }

/// <summary>
/// 写操作
/// </summary>
/// <param name="strPath"></param>
/// <param name="m_tPara"></param>
public static void SaveXmlPara(string strPath, syspara m_tPara)
{
XElement xe = XElement.Load(strPath);
xe.ReplaceNodes(
new XElement("通过", m_tPara.pass),
new XElement("不通过", m_tPara.fail),
new XElement("执行", m_tPara.testing),
new XElement("测试报告路径", m_tPara.testDataPath)
);
xe.Save(strPath);
}

/// <summary>
/// 创建操作
/// </summary>
public static void creadXmlFile(string strPath)
{
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("FormParamsSet",
new XElement("通过", 0),
new XElement("不通过", 0),
new XElement("执行", 0),
new XElement("测试报告路径", 0)
)
);
doc.Save(strPath);
}

}

public struct syspara
{
public long pass;//通过
public long fail;//不通过
public long testing;//执行
public string testDataPath;//测试报告路径
}

xml效果图:

其他类调用实例:

xmlOp1.creadXmlFile(AppDomain.CurrentDomain.BaseDirectory + "Op1.xml");
xmlOp1.readXmlPara(AppDomain.CurrentDomain.BaseDirectory + "Op1.xml", ref syspara);
syspara.fail = 1;
syspara.testDataPath = "11";
xmlOp1.SaveXmlPara(AppDomain.CurrentDomain.BaseDirectory + "Op1.xml", syspara);

 

posted @ 2020-09-28 16:38  SHW03  阅读(174)  评论(0编辑  收藏  举报