Parse XML and get elements from it using C# -


i have xml file such below:

<host>     <status state="up" reason="arp-response" reason_ttl="0"/>     <address addr="128.208.188.2" addrtype="ipv4"/>     <address addr="00:19:d1:3d:65:85" addrtype="mac" vendor="intel corporate"/>     <hostnames>         <hostname name="d0slf4.phys.washington.edu" type="ptr"/>     </hostnames>     <times srtt="1000" rttvar="5000" to="100000"/> </host>  <host>     <status state="up" reason="arp-response" reason_ttl="0"/>     <address addr="128.208.188.3" addrtype="ipv4"/>     <address addr="3c:94:d5:ac:18:7d" addrtype="mac" vendor="juniper networks"/>     <hostnames>         <hostname name="xe-0-3-2-&#45;1378.uwar-atg-1.infra.washington.edu" type="ptr"/>     </hostnames>     <times srtt="92000" rttvar="92000" to="460000"/> </host> 

the above code sample of 2 objects in large file. i'd hosts in file, , each one, show it's name, ipv4 address, , vendor.

i've been doing searching last hour, , while i've found examples, none of them fit need (sorry i'm new xml parsing).

here's code i've been trying (incomplete, because don't know go next):

string path = ""\\thor\test$\datasubnetscans\" + _readablesubnet + ".xml";  xmldocument xmldoc = new xmldocument(); xmldoc.load(path);  xmlnodelist hosts = xmldoc.getelementsbytagname("host"); foreach (xmlnode host in hosts)  {     // elements (fqdn, ipv4, vendor)     xmlnodelist fqdn = this.getelementsbytagname("hostname"); } 

the line of code inside foreach loop wrong, guess. can see above, i'm trying create list of elements, , each one, grab hostname name, ipv4 address, , vendor.

i understand little different reading text between <> tags, , have use attributes["name"].value.

i'm not sure if using xmlnodelist inside foreach loop way this, because each element has 2 elements, need way select them individually. doing should allow me select index right?

could point me in right direction?

thanks bunch, , please let me know if need additional information.

the following methods helpful:

you can retrieve information follows:

foreach (xmlnode host in hosts)  {     var hostname = ((xmlelement) host.selectsinglenode("hostnames/hostname")).getattribute("name");     var ipv4address = ((xmlelement) host.selectsinglenode("address[@addrtype='ipv4']")).getattribute("addr");     var vendor = ((xmlelement) host.selectsinglenode("address[@addrtype='ipv6']")).getattribute("vendor");     // add list } 

the sample assumes structure of xml document same , elements contained node. might need add checks or refine xpath queries if structure varies.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -