C # XML creation parsing, XML formatting,
Import namespace:
VS needs to add reference system. XML to the project; add using System. XML and using System. IO to the Code;
XML example:
|
<? 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 parsing:
Method 1:
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;
}
Method 2:
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 Creation
XmlDocument xmlDoc = new XmlDocument ();
// Create the root node
XmlDoc. LoadXml ("<? Xml version = '1. 0' encoding = 'utf-8'?> <MSG> </MSG> ");
XmlElement root = xmlDoc. DocumentElement;
// Create a level-1 Node
XmlElement flight = xmlDoc. CreateElement ("flight ");
// Create the second-level node
XmlElement flightPlan = xmlDoc. CreateElement ("flightPlan ");
XmlElement fpid = xmlDoc. CreateElement ("fpid ");
Fpid. InnerText = 32;
FlightPlan. AppendChild (fpid );
// Create the second node
XmlElement fpflag = xmlDoc. CreateElement ("fpflag ");
Fpflag. InnerText = 1;
Fpflag. SetAttribute ("name", "fpflag ");
FlightPlan. AppendChild (fpflag );
Flight. AppendChild (flightPlan );
Root. AppendChild (flight );
XML format
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 ();
}