I am trying to compare XML user input to a valid XML string. What I do is remove the values from the user input and compare it to the valid XML. At the bottom you can see my code. But as you can see in the XML examples the user input the goodslines
has two goodsline
children and fewer children. How can i alter my code so that it can this case would return true when compared? Thanks in advance
Valid XML
<?xml version="1.0" encoding="Windows-1252"?>
<goodslines>
<goodsline>
<unitamount></unitamount>
<unit_id matchmode="1"></unit_id>
<product_id matchmode="1"></product_id>
<weight></weight>
<loadingmeter></loadingmeter>
<volume></volume>
<length></length>
<width></width>
<height></height>
</goodsline>
</goodslines>
User input
<?xml version="1.0" encoding="Windows-1252"?>
<goodslines>
<goodsline>
<unitamount>5</unitamount>
<unit_id matchmode="1">colli</unit_id>
<product_id matchmode="1">1109</product_id>
<weight>50</weight>
<loadingmeter>0.2</loadingmeter>
<volume>0.036</volume>
<length>20</length>
<width>20</width>
<height>90</height>
</goodsline>
<goodsline>
<unitamount>12</unitamount>
<unit_id matchmode="1">drums</unit_id>
<product_id matchmode="1">1109</product_id>
<weight>345</weight>
</goodsline>
</goodslines>
Code
public static string Format(string xml)
{
try
{
var stringBuilder = new StringBuilder();
var element = XDocument.Parse(xml);
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true,
IndentChars = new string(' ', 3),
NewLineChars = Environment.NewLine,
NewLineOnAttributes = false,
NewLineHandling = NewLineHandling.Replace
};
using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
element.Save(xmlWriter);
return stringBuilder.ToString();
}
catch(Exception ex)
{
return "Unable to format XML" + ex;
}
}
public static bool Compare(string xmlA, string xmlB)
{
if(xmlA == null || xmlB == null)
return false;
var xmlFormattedA = Format(xmlA);
var xmlFormattedB = Format(xmlB);
return xmlFormattedA.Equals(xmlFormattedB, StringComparison.InvariantCultureIgnoreCase);
}
public static string NoText(string request)
{
string pattern = @"<.*?>";
Regex rg = new Regex(pattern);
var noTextArr = rg.Matches(request)
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
string noText = string.Join("", noTextArr);
return noText;
}