|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Text; |
| 4 | +using System.Xml; |
| 5 | +using System.Xml.Linq; |
| 6 | + |
| 7 | +namespace CnE2PLC.Helpers; |
| 8 | + |
| 9 | +public static class XMLHelper |
| 10 | +{ |
| 11 | + public static XmlNode CreateGenericXmlNode() |
| 12 | + { |
| 13 | + XmlDocument document = new XmlDocument(); |
| 14 | + return document.CreateNode(XmlNodeType.Element, "Generic", ""); |
| 15 | + } |
| 16 | + |
| 17 | + public static string GetNamedAttributeItemValue(this XmlNode node, string name) |
| 18 | + { |
| 19 | + return node.Attributes?.GetNamedItem(name)?.Value ?? String.Empty; |
| 20 | + } |
| 21 | + |
| 22 | + public static string GetNamedAttributeItemInnerText(this XmlNode node, string name) |
| 23 | + { |
| 24 | + return node.Attributes?.GetNamedItem(name)?.InnerText ?? String.Empty; |
| 25 | + } |
| 26 | + |
| 27 | + public static int? GetNamedAttributeItemInnerTextAsInt(this XmlNode node, string name) |
| 28 | + { |
| 29 | + return int.TryParse(node.GetNamedAttributeItemInnerText(name), out var value) ? value : null; |
| 30 | + } |
| 31 | + |
| 32 | + public static DateTime? GetNameAttributeItemInnerTextAsDateTime(this XmlNode node, string name) |
| 33 | + { |
| 34 | + string input = node.GetNamedAttributeItemInnerText(name); |
| 35 | + var sp = input.Split(' '); |
| 36 | + input = sp[1] + " " + sp[2] + ", " + sp[4] + " " + sp[3]; |
| 37 | + return DateTime.TryParse(input, out DateTime dt) ? dt : null; |
| 38 | + // Sat May 11 10:43:06 2024 |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + public static XmlNode SelectSingleNode(this XmlNode node, string name, XmlNode defaultIfNull) |
| 43 | + { |
| 44 | + return node.SelectSingleNode(name) ?? defaultIfNull; |
| 45 | + } |
| 46 | + |
| 47 | + public static string GetChildNodeInnerText(this XmlNode node, string name, bool useLast) |
| 48 | + { |
| 49 | + XmlNode? child = useLast ? node.ChildNodes.Cast<XmlNode>().LastOrDefault(n => n?.Name == name, null) : node.ChildNodes.Cast<XmlNode>().FirstOrDefault(n => n?.Name == name, null); |
| 50 | + return child == null ? String.Empty : child.InnerText; |
| 51 | + } |
| 52 | + |
| 53 | + public static bool AttributeExists(this XmlNode node, string name) |
| 54 | + { |
| 55 | + return node.Attributes?.GetNamedItem(name) != null; |
| 56 | + } |
| 57 | + |
| 58 | + public static bool AttributeExists(this XmlNode node, string name, out XmlNode attribute) |
| 59 | + { |
| 60 | + XmlNode? temp = node.Attributes?.GetNamedItem(name); |
| 61 | + if (temp != null) |
| 62 | + { |
| 63 | + attribute = temp; |
| 64 | + return true; |
| 65 | + } |
| 66 | + attribute = CreateGenericXmlNode(); |
| 67 | + return false; |
| 68 | + |
| 69 | + } |
| 70 | +} |
0 commit comments