欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# XML创建解析、XML格式化

程序员文章站 2022-04-03 08:13:19
导入命名空间: VS需要在项目中添加引用system.XML; 代码中添加 using System.XML和using System.IO; XML范例: ValidFlig ......

导入命名空间:

VS需要在项目中添加引用system.XML; 代码中添加 using System.XML和using System.IO;

 

XML范例:

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

<MSG>

  <HEADINFO>

    <TYPE>ValidFlight</TYPE>

  </HEADINFO>

  <ValidFlight>

    <Flight>

      <Runway>3</Runway>

      <Stand>27</Stand>

      <FlightID>436179</FlightID>

    </Flight>

    <Flight>

      <Runway>3</Runway>

      <FlightID>436180</FlightID>

    </Flight>

</ValidFlight>

</MSG>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

XML解析:

方法一:

XmlNode rootNode = XDoc.SelectSingleNode("/MSG/ValidFlight");

foreach (XmlNode Xnode in rootNode.ChildNodes)
{
        int FlightId = Convert.ToInt32(Xnode.SelectSingleNode("FlightID").InnerText);

        string RunWay = Xnode.SelectSingleNode("Runway") == null ? null : Xnode.SelectSingleNode("Runway").InnerText;

       string Stand = Xnode.SelectSingleNode("Stand") == null ? null : Xnode.SelectSingleNode("Stand").InnerText;
}

方法二:

XmlNode nodelist= XDoc.SelectSingleNode("MSG/ValidFlight");

foreach (XmlNode Xnode in nodelist)
{
     int FlightId = Convert.ToInt32(Xnode["FlightID"].InnerText);

    string RunWay = Xnode["Runway"]== null ? null : Xnode.Xnode["Runway"].InnerText;

    string Stand = Xnode["Stand"] == null ? null :Xnode["Stand"].InnerText;
}

XML创建

XmlDocument xmlDoc = new XmlDocument();

//创建根节点

xmlDoc.LoadXml("<?xml version = '1.0' encoding='UTF-8'?><MSG></MSG>");

XmlElement root = xmlDoc.DocumentElement; 

//创建一级节点

XmlElement flight = xmlDoc.CreateElement("flight");

//创建第二级节点

XmlElement flightPlan = xmlDoc.CreateElement("flightPlan");

XmlElement fpid = xmlDoc.CreateElement("fpid");

fpid.InnerText = 32;

flightPlan.AppendChild(fpid);

//创建第二个节点

XmlElement fpflag = xmlDoc.CreateElement("fpflag");
fpflag.InnerText = 1;

fpflag.SetAttribute("name","fpflag");

flightPlan.AppendChild(fpflag);

flight.AppendChild(flightPlan);

root.AppendChild(flight);

XML格式化

private static string formatXml(XmlDocument xml)
{
XmlDocument xd = xml as XmlDocument;
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = null;
try
{
xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xtw.Indentation = 1;
xtw.IndentChar = '\t';
xd.WriteTo(xtw);
}
finally
{
if (xtw == null)
xtw.Close();
}
return sb.ToString();
}