{"id":8506,"date":"2024-05-06T08:16:05","date_gmt":"2024-05-06T07:16:05","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=8506"},"modified":"2024-05-06T08:24:51","modified_gmt":"2024-05-06T07:24:51","slug":"c-untyped-xml-parsing","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-untyped-xml-parsing\/","title":{"rendered":"C# Untyped Xml Parsing"},"content":{"rendered":"\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"csharp\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">using System.Xml;\r\n\/\/ ...\r\n\r\npublic static class XmlNodeExtensions\r\n{\r\n    public static XmlNode PathFirstNode(this XmlNode node, string path) => XmlNodeHelpers.PathFirstNode(node, path);\r\n    public static string PathFirstValue(this XmlNode node, string path, string defValue = default) => XmlNodeHelpers.PathFirstValue(node, path, defValue);\r\n    public static T PathFirstValue&lt;T>(this XmlNode node, string path, T defValue = default) => XmlNodeHelpers.PathFirstValue(node, path, defValue);\r\n    public static IEnumerable&lt;XmlNode> PathSelectNodes(this XmlNode node, string path) => XmlNodeHelpers.PathSelectNodes(node, path);\r\n}\r\n\r\npublic class XmlNodeHelpers\r\n{\r\n    public static XmlNode PathFirstNode(XmlNode n, string path) => n.SelectNodes(path).OfType&lt;XmlNode>().FirstOrDefault();\r\n    public static string PathFirstValue(XmlNode n, string path, string defValue = default) => PathFirstValue&lt;string>(n, path, defValue);\r\n    public static T PathFirstValue&lt;T>(XmlNode n, string path, T defValue = default)\r\n    {\r\n        var value = PathFirstNode(n, path)?.InnerText;\r\n        if (value == null) return defValue;\r\n        if (value is T t) return t;\r\n        if (typeof(T) == typeof(string))\r\n        {\r\n            return (T)(object)$\"{value}\";\r\n        }\r\n        var basicType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);\r\n        try\r\n        {\r\n            return (T)Convert.ChangeType(value, basicType);\r\n        }\r\n        catch { } \/\/ ignore value conversion error\r\n        return defValue;\r\n    }\r\n\r\n    public static IEnumerable&lt;XmlNode> PathSelectNodes(XmlNode n, string path) => n.SelectNodes(path).OfType&lt;XmlNode>();\r\n}\r\n\r\n\/\/ usage:\r\nvar doc = new XmlDocument();\r\ndoc.LoadXml(orderMessagesXml);\r\n\r\nvar orders = new List&lt;CommonOrder>();\r\nforeach (var orderMessage in doc.PathSelectNodes(\"\/Orders\/Order\"))\r\n{\r\n    var order = new CommonOrder();\r\n    orders.Add(order);\r\n    var orderType = (OrderType)orderMessage.PathFirstValue(\"OrderType\", 0);\r\n    order.DeliveryDate = GetDateTimeFromInput(message.PathFirstValue(\"DeliveryDate\", null));\r\n    \/\/ ...\r\n    \r\n    foreach (var article in orderMessage.PathSelectNodes(\"Article\"))\r\n    {\r\n        var article = new CommonArticle();\r\n        order.Articles.Add(article);\r\n        article.GTIN = article.PathFirstValue(\"GTIN\");\r\n        article.Quantity = article.PathFirstValue&lt;double>(\"Quantity\");\r\n        \/\/ ...\r\n    }\r\n}\r\n<\/pre><\/div>\n\n\n\n<p>Build untyped Xml<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"csharp\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">using System.Xml;\nusing System.Xml.Linq;\n\npublic static IEnumerable&lt;XElement> GetElements(string[,] parameters)\n{\n    for (int i = 0; i &lt; parameters.GetLength(0); i += 1)\n    {\n        var key = parameters[i, 0];\n        var value = parameters[i, 1];\n        if (value == null) continue; \/\/ skip null values\n        yield return new XElement(key, new XText(value));\n    }\n}\n\nvar doc = new XDocument(new XElement(\"Orders\"));\n\nvar order = new XElement(\"Order\",\n        GetElements(new string[,] {\n        { \"OrderType\", \"55\" },\n        { \"DeliveryDate\", DateToStr(deliveryDate) }\n        });\n        \nforeach (var article in articlesList)\n{\n     var articleLine = new XElement(\"Article\",\n         GetElements(new string[,] {\n             { \"GTIN\", article.GTIN },\n             { \"Quantity\", $\"{article.Quantity}\" }\n         })\n     );\n     \n    order.Add(articleLine);\n}\n\ndoc.Root.Add(order);\nvar textWriter = new Utf8StringWriter();\ndoc.Save(textWriter, SaveOptions.None);\nreturn textWriter.ToString();<\/pre><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Build untyped Xml<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-8506","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/8506","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=8506"}],"version-history":[{"count":5,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/8506\/revisions"}],"predecessor-version":[{"id":8513,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/8506\/revisions\/8513"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=8506"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=8506"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=8506"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}