c\#xml 읽 기


 





<?xml version="1.0" encoding="utf-8"?>

<PersonF xmlns="" Name="(test)work hard work smart!">

  <person Name="Person1">

    <ID>1</ID>

    <Name>XiaoA</Name>

    <Age>59</Age>

  </person>

  <person Name="Person2">

    <ID>2</ID>

    <Name>XiaoB</Name>

    <Age>29</Age>

  </person>

  <person Name="Person3">

    <ID>3</ID>

    <Name>XiaoC</Name>

    <Age>103</Age>

  </person>

  <person Name="Person4">

    <ID>4</ID>

    <Name>XiaoD</Name>

    <Age>59</Age>

  </person>

</PersonF> 


  
 
Code:       。
 



?





public  void TestXML()

{

    XmlDocument doc = new XmlDocument();

    string path = "http://www.cnblogs.com/MyDocument/Person.xml";

    try

    {

 

        //doc.Load(Server.MapPath()

        doc.Load(path);

 

        //1、         

        XmlNode node = doc.SelectSingleNode("PersonF");

 

        //2、         

        XmlNodeList nodeList1 = doc.SelectNodes("PersonF/person");

 

        //3.1             :   Person2      Name InnerText

        XmlNodeList nodeList = doc.DocumentElement.GetElementsByTagName("person");

        foreach (XmlNode node2 in nodeList1) //     nodeList  

        {

            if (node2.Attributes["Name"].InnerText == "Person2")

            {

                Console.WriteLine(node2.ChildNodes[1].InnerText);

 

            }

        }

 

        //3.2   ID 2           Name InnerText

        XmlNode node3 = doc.SelectSingleNode("PersonF/person[ID=2]");

        string strNode3 = node3.ChildNodes[1].InnerText;

 

        //3.3           ID 2   

        XmlNodeList nodeList2 = doc.SelectNodes("//person//ID");

        XmlNode node4 = null;

        foreach (XmlNode node5 in nodeList2)

        {

            if (node5.InnerText == "2")

            {

                node4 = node5;

                break;

            }

        }

        Console.WriteLine(node4.InnerText);

 

        //4、       

        string Name = node.Attributes["Name"].InnerText;

 

        //5        

        node.Attributes["Name"].InnerText = "work hard work smart!";

        doc.Save(path);

 

        //6         

        XmlTextReader reader = new XmlTextReader(path);

        XmlElement root = doc.DocumentElement;//     

        XmlElement tagOuter = doc.CreateElement("person");

        //      

        tagOuter.SetAttribute("Name", "Person5");

        XmlElement tagIN_Name = doc.CreateElement("Name");

        XmlElement tagIN_ID = doc.CreateElement("ID");

        tagIN_Name.InnerText = "work hard work smart!";

        tagIN_ID.InnerText = "32";

        tagOuter.AppendChild(tagIN_Name);

        tagOuter.AppendChild(tagIN_ID);

        root.AppendChild(tagOuter);//  tagOuter XML     

        reader.Close();

        doc.Save(path);

    }

    catch (System.Exception e)

    {

        throw new Exception(e.Message);

    }

} 

좋은 웹페이지 즐겨찾기