c# - Get XML attribute and value from elements -
i being provided following xml, no ability change structure:
<reportspec> <report reportname="reportname1" filtermode="container" destination="emailtouser:loggedinuser" format="pdf" alertsource="all" criticalstatus="true"> <filter students="all" /> </report> <report reportname="reportname1" filtermode="container" destination="emailtousergroup:useradmins" format="pdf" alertsource="all" criticalstatus="false"> <filter testscore="1234" /> </report> <report reportname="reportname1" filtermode="container" destination="dir:\\net.path.com\reports" format="pdf" alertsource="failing"> <filter grade="all" /> </report> <report reportname="reportname1" filtermode="container" destination="emailto:a@b.com,joe@schmoe.com" format="pdf" alertsource="failing"> <filter course="programming" /> </report> </reportspec>
i using c# (.net 4.5), , need pick attribute name , value of <filter>
elements, become part of app logic later in code (that is, want collect testscore="1234"
entire string, , use later on). using xmlserializer
, streamreader
load xml document (but willing change approach, if need be). i've done paste special --> xml classes
in visual studio 2013, filters class gets created won't allow me perform foreach
on elements. can done, , how?
you can use xmldocument class
using system; using system.io; using system.xml; namespace consoleapplication1 { class program { static void main(string[] args) { var file = file.readalltext("c:\\temp\\file.xml"); var xmlfile = new xmldocument(); xmlfile.loadxml(file); var filterelements = xmlfile.getelementsbytagname("filter"); foreach (xmlnode filternode in filterelements) { var filtername = filternode.attributes[0].name; var filtertext = filternode.attributes[0].innerxml; var destination = filternode.parentnode.attributes["destination"].innertext; var message = string.format("the destination {0} filter {1} {2}", destination, filtername, filtertext); console.writeline(message); } console.readkey(); } }
and output be:
the destination emailtouser:loggedinuser filter students all
the destination emailtousergroup:useradmins filter testscore 1234
the destination dir:\net.path.com\reports filter grade all
the destination emailto:a@b.com,joe@schmoe.com filter course programming