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

2021-02-15 19:15

阅读:537

导入命名空间:

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

 

XML范例:

 

    ValidFlight

 

 

   

      3

      27

      436179

   

   

      3

      436180

   

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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("");

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();
}

 


评论


亲,登录后才可以留言!