I have multiple Code Tables at the bottom of the XML that I am processing and I would like to lookup a code that comes from the top portion of the XML and get the CodeText from a table at the bottom of the XML.
Here are two of the CodeTables:
<CodeTable Name="Codes - Days of Week">
<CodeText CodeValue="" />
<CodeText CodeValue="1">SUNDAY</CodeText>
<CodeText CodeValue="2">MONDAY</CodeText>
<CodeText CodeValue="3">TUESDAY</CodeText>
<CodeText CodeValue="4">WEDNESDAY</CodeText>
<CodeText CodeValue="5">THURSDAY</CodeText>
<CodeText CodeValue="6">FRIDAY</CodeText>
<CodeText CodeValue="7">SATURDAY</CodeText>
</CodeTable>
<CodeTable Name="Codes - Bus Type">
<CodeText CodeValue="" />
<CodeText CodeValue="0">NOT A BUS</CodeText>
<CodeText CodeValue="1">SCHOOL (PUBLIC OR PRIVATE)</CodeText>
<CodeText CodeValue="2">TRANSIT</CodeText>
<CodeText CodeValue="3">INTERCITY</CodeText>
<CodeText CodeValue="4">CHARTER</CodeText>
<CodeText CodeValue="5">OTHER</CodeText>
</CodeTable>
I am able to use the following lines of code to get to the code table:
string CodeTableName = "Codes - Days of Week";
XmlNode CodeTableNode = doc.SelectSingleNode("//CodeTable[@Name=\"" + Convert.ToString(CodeTableName) + "\"]");
And I have been able to use the following to get the CodeText for Bus Type = 0:
XmlNode CodeTextNode = doc.SelectSingleNode("//CodeText[@CodeValue=\"" + Convert.ToString(BusCode) + "\"]");
code_text = CodeTextNode.InnerText;
Console.WriteLine(code_text);
What I would like to be able to do is put both of these together somehow? So I can get to the CodeTable I need and then pull the correct CodeText based on the CodeValue.
If you use LinqToXml you could do the following:
using System.Linq;
using System.Xml.Linq;
// [...]
var codeKey = "0";
var name = "Codes - Bus Type";
var doc = XDocument.Load("bla");
var code = doc.Descendants().Where(
d => d.Name == "CodeText" &&
d.Parent.Attribute("Name").Value == name &&
d.Attribute("CodeValue").Value == codeKey).FirstOrDefault().Value;
In productive code I'd make sure that you first check for null
before the last .Value
call. But otherwise this should work.