We came across a situation where one of our BA wants to have X paths listed in his specification for a given XML and the XML which he is looking at is huge. So he asked our development team to create tool where he can give the XML and can get all the X paths list out where he can save.
Below is the details of the function where given an XML document we can generate X paths out of it.
Below is the details of the function where given an XML document we can generate X paths out of it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ClassLibrary1
{
public class XmltoXpath
{
public string Xpathlist = string.Empty;
public void getXpathsfromxml(string xmlcontent)
{
try
{
XmlDocument dom = new XmlDocument();
try
{
dom.LoadXml(xmlcontent);
}
catch(Exception e)
{
throw new Exception("Error: file is not a valid xml. Original error: " + e.Message);
}
XmlNode rootnode = (XmlNode)dom.DocumentElement;
EnumerateChildren(ref rootnode, "/" + rootnode.Name);
}
catch(Exception ex)
{
throw new Exception("Error: generating Xpaths from xml. Original error: " + ex.Message);
}
}
private void EnumerateChildren(ref XmlNode elem, string Xpath)
{
EnumerateAttributes(ref elem, Xpath);
XmlNode children;
if(elem.HasChildNodes)
{
foreach (XmlNode child in elem.ChildNodes)
{
children = child;
if (child.Name=="#text")
{
Xpathlist = Xpathlist + string.Format("{0}=\"{1}\"\r\n",Xpath, child.Value);
}
else
{
EnumerateChildren(ref children, Xpath + "/" + child.Name);
}
}
}
}
private void EnumerateAttributes(ref XmlNode node,string Xpath)
{
try
{
XmlAttributeCollection attributes = node.Attributes;
foreach(XmlAttribute att in attributes)
{
Xpathlist = Xpathlist + string.Format("{0}/@{1}\r\n",Xpath, att.OuterXml);
}
}
catch(Exception ex)
{
}
}
}
}
No comments:
Post a Comment