panjo
panjo

Reputation: 3515

read xml file and extract some integer value

I have xml file with content like this

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<REPLY>
  <DATA BYTE='116' />
  <DATA BYTE='88' />
  <DATA BYTE='15' />
  <DATA BYTE='0' />
from this
  <DATA BYTE='44' />  
  <DATA BYTE='1' />
  <DATA BYTE='0' />
  <DATA BYTE='0' />
to this
  <DATA BYTE='0' />
  <DATA BYTE='0' />
.....
  <DATA BYTE='255' />
  <DATA BYTE='255' />
  <DATA BYTE='255' />
  <DATA BYTE='0' />
</REPLY>

I want to read 4 lines from this to this, actually I want to extract values 44,1,0,0 from these 4 lines. Values are dynamic, structure of document will not change (at least in first 15 lines).

What is the best way to do this?

Upvotes: 0

Views: 280

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

  1. Load your XML into XDocument instance using XDocument.Parse() or XDocument.Load() methods.
  2. Query your XML using LINQ to XML:
var values = doc.Root.Elements("DATA").Skip(4)
                                      .Take(4)
                                      .Select(x => (int)x.Attribute("BYTE"))
                                      .ToList();

I assumed that REPLY is a root element in your XML. If it's not, you have to query for it first:

var reply = doc.Descendants("REPLY").First();
var values = reply.Elements("DATA").Skip(4)
                                   .Take(4)
                                   .Select(x => (int)x.Attribute("BYTE"))
                                   .ToList();

Upvotes: 10

Related Questions