C# XML創建解析、XML格式化
導入命名空間:
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();
}
C# XML創建解析、XML格式化