XML创建读写更新 和 Json 读写

C#中XML 类有XMLDocument和XDocument ,其中XMLDocument是标准的DOM。因此主要采用这种方式

1)XMLDocument 写入

//XmlDocument 标准dom 模型,写XML        


            XmlDocument doc = new XmlDocument();
            XmlNode rootNode = doc.CreateElement("Identity");
            doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            XmlAttribute versionAttr = doc.CreateAttribute("Version");
            versionAttr.Value = "2.0.0.0";
            rootNode.Attributes.Append(versionAttr);
            XmlNode childNode = doc.CreateElement("Name");
            XmlAttribute childAttr = doc.CreateAttribute("Font");
            childAttr.Value = "Arial";
            childNode.Attributes.Append(childAttr);
            childNode.InnerText = "test";
            rootNode.AppendChild(childNode);
            doc.AppendChild(rootNode);
            doc.Save(@"C:\Users\duke chen\Desktop\test.xml");

2) XMLDocument read 

XmlDocument支持使用xpath表达式选择文档中节点,方法:
SelectNodes(String expression)
SelectSingleNode(string expression)
SelectNodes 返回符合expression表达式的所有元素,返回值为XmlNodeList,比如本例子是通过XmlNodeList
nodelist = xmlDoc.SelectNodes("/CameraGroup/Camera");获取所有的Camera节点。

string xmlFileStr = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Config.xml");//读取xml文件字符串
            Stream xmlfileSteram = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xmlFileStr));//转为内存流
            XmlDocument xmlconfig = new XmlDocument();
            xmlconfig.Load(xmlfileSteram);//or xmlconfig.Load(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"); //加载到xml文档中
            XmlElement element = xmlconfig.DocumentElement;
            Console.WriteLine("====================================================");
            Console.WriteLine("schoolId:" + element.SelectSingleNode("schoolId").InnerText);
            Console.WriteLine("shcoolName:" + element.SelectSingleNode("shcoolName").InnerText);

方法二:

if (File.Exists(filePath) && nodeName != "")
                 {
                    XmlDocument xmlDoc = new XmlDocument();//新建XML文件
                    xmlDoc.Load(filePath);//加载XML文件 
                  XmlNode xm = xmlDoc.GetElementsByTagName(nodeName)[0];
                   result = xm.InnerText;

                }

3) XML 和Dataset ,string 的相互转换

C# 创建 读取 更新 XML文件

public static class XmlHelper
{
/// <summary>
/// 读取节点值
/// </summary>
/// <param name="Path">XML文件路径</param>
/// <param name="Node1">第一级节点</param>
/// <param name="Node2">第二级节点</param>
/// <returns></returns>
public static string GetXmlReader(string Path, string Node1, string Node2)
{
XmlDocument myDc = new XmlDocument();
myDc.Load(Path);
return myDc.SelectSingleNode(Node1).SelectSingleNode(Node2).InnerText;
}


/// <summary>
/// 创建一个XML文件
/// </summary>
/// <param name="Path">XML文件路径</param>
/// <param name="key">List</param>
/// <param name="value">List</param>
public static void CreateXML(string Path, List<string> key, List<string> value)
{
XmlDocument xmlDoc = new XmlDocument();
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
XmlNode root = xmlDoc.CreateElement("Config");
xmlDoc.AppendChild(root);

for (int i = 0; i < key.Count; i++)
{
CreateNode(xmlDoc, root, key[i].ToString(), value[i].ToString());
}
try
{
xmlDoc.Save(Path);
}
catch (Exception e)
{
}
}


/// <summary>
/// 创建一个XML文件中的 节点
/// </summary>
/// <param name="xmlDoc"></param>
/// <param name="parentNode"></param>
/// <param name="name"></param>
/// <param name="value"></param>
public static void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
}


/// <summary>
/// 更新XML中指定节点的值
/// </summary>
/// <param name="Path">XML文件路径</param>
/// <param name="NodeName">需要更改的节点</param>
/// <param name="NodeValue">需要更新的节点值</param>
public static void UpdateNode(string Path, string NodeName, string NodeValue)
{
XmlDocument doc = new XmlDocument();
doc.Load(Path);
XmlNode xn = doc.SelectSingleNode("//" + NodeName + "");
xn.InnerText = NodeValue;

if (xn != null) xn.InnerText = nodeValue;
            xn.Attributes["Value"].Value = "test";
doc.Save(Path);
}

}

C# 读写Json

引用 JSon Dll

JsonConvert , JArray , JObject 对象,KV 来读写

var systemTypeUpgradeMapping =
                    JsonConvert.DeserializeObject<Dictionary<string,string>>(
                        File.ReadAllText(SystemTypeUpgradeMapping));

var selectedAudioDevices = new SelectedAudioDevices(inputDevice, outputDevice);
                File.WriteAllText(
                    _audioDeviceConfigFilePath,
                    JsonConvert.SerializeObject(selectedAudioDevices, Formatting.Indented));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值