In a more abstract level, the problem is to parse either an attribute or a node named num
or code
. Considering C# already has libraries to parse XML documents (and such solutions are also acceptable according to your comments), it's more natural to take advantage of these libraries. The following function will return the specified attribute/node.
static string ParseNode(XmlElement e, string AttributeOrNodeName)
{
if (e.HasAttribute(AttributeOrNodeName))
{
return e.GetAttribute(AttributeOrNodeName);
}
var node = e[AttributeOrNodeName];
if (node != null)
{
return node.InnerText;
}
throw new Exception("The input element doesn't have specified attribute or node.");
}
A test code is like
var doc = new XmlDocument();
var xmlString = "<test><node><num>123456789</num><code>012</code></node>\r\n"
+ "<node><code>012</code><num>123456789</num></node>\r\n"
+ "<node num=\"123456789\" code=\"012\" />\r\n"
+ "<node code=\"012\" num=\"123456789\" />\r\n"
+ "<node code=\"012\"><num>123456789</num></node>\r\n"
+ "<node num=\"123456789\"><code>012</code></node>\r\n"
+ @"<node>
<num>123456789</num>
<code>012</code>
</node>
</test>";
doc.LoadXml(xmlString);
foreach (var num in doc.DocumentElement.ChildNodes.Cast<XmlElement>().Select(x => ParseNode(x, "num")))
{
Console.WriteLine(num);
}
Console.WriteLine();
foreach (var code in doc.DocumentElement.ChildNodes.Cast<XmlElement>().Select(x => ParseNode(x, "code")))
{
Console.WriteLine(code);
}
In my environment (.NET 4), the code captures all the num
and code
values.