Unity上使用Linq To XML

using UnityEngine;
using System.Collections;
using System.Linq;
using System.Xml.Linq;
using System;
 
public class XML {
//static string xmlpath = Application.persistentDataPath + @"myXML";//平台相关的路径(移动端)
static string xmlpath=Application.dataPath+@"mydfdfXML";//电脑上的路径,移动端没有这个访问权限
/// <summary>
/// 初始化一个XML文件
/// </summary>
public static void CreateXMLDocument()
{
XElement root = new XElement("XMLContent",
new XElement("Herb1",new XAttribute("MyVaule","0")),
new XElement("Herb2",new XAttribute("MyVaule","0")),
new XElement("Herb3",new XAttribute("MyVaule","0")),
new XElement("Pill1",new XAttribute("MyVaule","0")),
new XElement("Pill2",new XAttribute("MyVaule","0")),
new XElement("Pill3",new XAttribute("MyVaule","0")),
new XElement("Level",new XAttribute("MyVaule","0")),
new XElement("Root","root")
);
root.Save(xmlpath);
}
public static XElement LoadXMLFromFile()
{
XElement root = XElement.Load(xmlpath);
return root;
}
public static void SetElementValue(string name, string value)
{
XElement root = LoadXMLFromFile();
root.Element(name).SetAttributeValue("MyVaule", value);
root.Save(xmlpath);
}
/// <summary>
/// 在根节点元素之前添加新的元素
/// </summary>
/// <param name="name">元素名字</param>
/// <param name="value">元素的值</param>
public static void AddElement(string name, string value)
{
XElement root = LoadXMLFromFile();
root.Element("Root").AddBeforeSelf(new XElement(name, new XAttribute("MyValue",value)));
root.Save(xmlpath);
}
/// <summary>
/// 删除指定的元素
/// </summary>
/// <param name="name">要删除的元素名称</param>
public static void RemoveElement(string name)
{
XElement root = LoadXMLFromFile();
root.Element(name).Remove();
root.Save(xmlpath);
}
/// <summary>
/// 根据元素名查找元素对应的值
/// </summary>
/// <param name="name">元素名</param>
/// <returns></returns>
public static string GetElementValue(string name)
{
XElement root = LoadXMLFromFile();
XAttribute xattr = root.Element(name).Attribute("MyVaule");
string s = xattr.Value;
return s;
}
}

http://blog.csdn.net/lyq5655779/article/details/7183350

1.写XML文件

[html] view plaincopy
 
  1. XElement xperson = new XElement("person");//根节点  
  2.             xperson.SetAttributeValue("age", 30);//设置属性  
  3.             XElement xperson1 = new XElement("person1");  
  4.             xperson1.Value = "tom";//设置 innerText值  
  5.             xperson1.SetAttributeValue("sex", "男");  
  6.             XElement xperson2 = new XElement("person2");  
  7.   
  8.             xperson.Add(xperson1);//加入到根结点  
  9.             xperson.Add(xperson2);  
  10.             string xml = xperson.ToString();  
  11.             Console.WriteLine(xml);  
  12.             using (Stream stream = File.OpenWrite(@"D:1.xml"))  
  13.             {  
  14.                 byte[] bytes = new byte[1024];  
  15.                 bytes = Encoding.UTF8.GetBytes(xml);  
  16.                 stream.Write(bytes, 0, bytes.Length);//写入文件  
  17.             }  


2.读取XML文件

  ----------如何读取xml文件的内容----------------

            using(Stream stream=File.OpenRead(@"D:1.xml"))
            {
               using(StreamReader reader= new StreamReader(stream))
               {
                   //从Reflector从可以看到TextReader的子类是StreamReader所以,可以直接用StreamReader来读取XML文档,传给XDocument.Load方法
                  XDocument xml=XDocument.Load(reader);//load里面
                  Console.WriteLine( xml.Root.ToString());//xml文档
                  Console.WriteLine(xml.Root.Nodes().ElementAt(0).ToString());//ElementAt()第几个子节点 
                  Console.WriteLine(xml.Root.Attribute("age").Value);//返回根节点的属性的值
                  XNode nodes=xml.Root.Nodes().ElementAt(0);
                  XElement e=nodes as XElement;
                  Console.WriteLine(e.Attribute("sex").Value);//读取第一个子节点的属性
                }
            
            }

3.读取App.Config

  using (Stream stream = File.OpenRead(@"D: et实例教程练习netXML练习XML练习App.config"))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    XDocument xml = XDocument.Load(reader);
                    XNode n1 = xml.Root.Nodes().ElementAt(0);//这就是<configuration> ------下面----<connectionStrings>
                    XElement e1 = n1 as XElement;
                    XNode n1_1 = e1.Nodes().ElementAt(0);//connectionStrings下面的<add .....>第一个
                    XNode n1_2 = e1.Nodes().ElementAt(1);//connectionStrings下面的<add .....>第一个
                    XElement e1_1 = n1_1 as XElement;
                    XElement e1_2 = n1_2 as XElement;
                    //Console.WriteLine("Name={0},Connection={1}", e1.Attribute("name").Value, e1.Attribute("connectionString").Value);
                    Console.WriteLine("第一个连接字符串的name={0},Connection={1}", e1_1.Attribute("name"), e1_1.Attribute("connectionString"));

                    Console.WriteLine("第一个连接字符串的name={0},Connection={1}", e1_2.Attribute("name"), e1_2.Attribute("connectionString"));


                }
            }
       


         

[csharp] view plaincopy
 
    1. using (Stream stream = File.OpenRead(@"D: et实例教程练习netXML练习XML练习App.config"))  
    2. {  
    3.   
    4.     using (StreamReader reader = new StreamReader(stream))  
    5.     {   
    6.         XDocument xml=XDocument.Load(reader);  
    7.         IEnumerable<XElement> XConnstr = xml.Root.Elements("connectionStrings");  
    8.       
    9.         Console.WriteLine(XConnstr.Count().ToString());  
    10.         if (XConnstr.Count() == 1)  
    11.         {  
    12.              XElement Connstr = XConnstr.ElementAt(0);  
    13.             foreach(XElement conn in Connstr.Elements("add"))  
    14.             {  
    15.                 string name = conn.Attribute("name").Value;  
    16.                 string Connection = conn.Attribute("connectionString").Value;  
    17.                 Console.WriteLine("Name={0},Age={1}", name, Connection);  
    18.               
    19.             }  
    20.           
    21.         }  
    22.     }  
    23.   

http://blog.csdn.net/xutao_ustc/article/details/6316933

<?xml version="1.0" encoding="utf-8" ?>
<UIConfig Count="1">
  <workflow name="OilInbound">
    <activity name="Started">
        <Input>
          <Page></Page>
          <Method></Method>
        </Input>
        <Brief>
          <Page>OilInboundTaskDetail</Page>
          <Method>GetTaskDetailModel</Method>       
        </Brief>
        <Detail>
          <Page>OilInboundTaskDetail</Page>
          <Method>GetTaskDetailModel</Method>
        </Detail>
        <DisplayName>任务创建</DisplayName>
    </activity>
    <activity name="OilCompositionAnalysis">
        <Input>
          <Page>OilAnalyzingDataInput</Page>
          <Method>GetOilAnalyzingDataInputModel</Method>
        </Input>
        <Brief>       
          <Page>OilAnalyzingDataBrief</Page>
          <Method>GetOilAnalyzingDataBriefModel</Method>
        </Brief>
        <Detail>
          <Page>OilAnalyzingDataDetail</Page>
          <Method>GetOilAnalyzingDataDetailModel</Method>
        </Detail>
        <DisplayName>化验</DisplayName>       
    </activity>
  </workflow>
</UIConfig>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml.Linq;
using System.Xml;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            XElement doc =  XElement.Load("..//..//data-config.xml");//根元素
            string sss = getStr(doc, "OilInbound", "Started", "Input", "Page");
            Console.WriteLine(sss);
            Console.ReadKey();
        }
        //如果当前元素的子元素只有一个,可以直接用.Element("elementName")来得到,如果是多个子元素就用Elements("elementName")得到
        private static string getStr(XElement doc,string workflowName,string stepName,string typeName,string pageMethod) {
            var strEle = from workflow in doc.Elements("workflow")
                              where (string)workflow.Attribute("name") == workflowName
                              select
                              new{
                               str = workflow.Elements("activity").TakeWhile(x => (string)x.Attribute("name") == stepName).First().Element(typeName).Element(pageMethod).Value
                              };
            return strEle.First().str;           
        }
    }  
}
原文地址:https://www.cnblogs.com/123ing/p/3918674.html