Import namespaces:
vs need to add reference system.xml to the project; The code adds using System.Xml and using System.IO;
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 One:
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 Two:
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 ();
Creating the root node
Xmldoc.loadxml ("<?xml Version = ' 1.0 ' encoding= ' UTF-8 '?><msg></msg>");
XmlElement root = xmldoc.documentelement;
Create a first-level node
XmlElement flight = xmldoc.createelement ("Flight");
Create a second-level node
XmlElement Flightplan = xmldoc.createelement ("Flightplan");
XmlElement fpid = xmldoc.createelement ("Fpid");
Fpid. InnerText = 32;
Flightplan.appendchild (FPID);
Create a second node
XmlElement Fpflag = xmldoc.createelement ("Fpflag");
Fpflag. InnerText = 1;
Fpflag. SetAttribute ("name", "Fpflag");
Flightplan.appendchild (Fpflag);
Flight. AppendChild (Flightplan);
Root. AppendChild (flight);
XML formatting
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 creation parsing, XML formatting