xml functions

class Xml { public static long XmlLong(String expression, string inputXml) { XElement xe; XDocument xd; long i; try { if (inputXml.StartsWith("<?xml")) { xd = XDocument.Parse(inputXml); } else { xd = XDocument.Load(new Uri(inputXml, UriKind.Relative).ToString()); } xe = xd.Root.DescendantsAndSelf().Elements().Where(d => d.Name == expression).First(); i = long.Parse(xe.Value); } catch (Exception ex) { Console.WriteLine("XmlLong, Expression \"" + expression + "\", inputXml \"" + inputXml + "\", Error: " + ex.Message); return 0; } return i; } public static int XmlInt(String expression, string inputXml) { XElement xe; XDocument xd; int i; try { if (inputXml.StartsWith("<?xml")) { xd = XDocument.Parse(inputXml); } else { xd = XDocument.Load(new Uri(inputXml, UriKind.Relative).ToString()); } xe = xd.Root.DescendantsAndSelf().Elements().Where(d => d.Name == expression).First(); i = Int32.Parse(xe.Value); } catch (Exception ex) { Console.WriteLine("XmlInt, Expression \"" + expression + "\", inputXml \"" + inputXml + "\", Error: " + ex.Message); return 0; } return i; } public static string XmlString(String expression, string inputXml) { XElement xe; XDocument xd; try { if (inputXml.StartsWith("<?xml")) { xd = XDocument.Parse(inputXml); } else { xd = XDocument.Load(new Uri(inputXml, UriKind.Relative).ToString()); } xe = xd.Root.DescendantsAndSelf().Elements().Where(d => d.Name == expression).First(); } catch (Exception ex) { Console.WriteLine("XmlString, Expression \"" + expression + "\", inputXml \"" + inputXml + "\", Error: " + ex.Message); return ""; } return xe.Value; } public static bool XmlBool(String expression, string inputXml) { XElement xe; XDocument xd = null; try { if (inputXml.StartsWith("<?xml")) { xd = XDocument.Parse(inputXml); } else { xd = XDocument.Load(new Uri(inputXml, UriKind.Relative).ToString()); } xe = xd.Root.DescendantsAndSelf().Elements().Where(d => d.Name == expression).First(); } catch (Exception ex) { Logging.Error("XML", "XmlBool, Expression \"" + expression + "\", inputXml \"" + xd.ToString() + "\", Error: " + ex.Message); return false; } if ((xe.Value == "true") || (xe.Value == "1")) { return true; } else { return false; } } }
Usage in comments because descriptions doesn't like line breaks.

1 Response

Example XML: xml.cs
----------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<document>
<XmlVersion>20150902.114930</XmlVersion>
<serial>00000</serial> <!-- Serial of device -->
</document>
----------------------------------

Example usage:

string version = Xml.XmlString("XmlVersion", @"c:\xml.cs");
int serial = Xml.XmlInt("serial", @"c:\xml.cs");

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.