ethem
ethem

Reputation: 2908

how to get the value from XML tag?

Below is the information I receive from DB. It's originally from an XML file, but this is stored in DB table and I can't change the situation. I need to work these way, since there is no more information available.

I read these in a dataset and my rows contains the 4 POSSIBLE ways.... I used Value1, Value2, Value3, Value4.... Is there a way to easily get these Values. Value 4 is special. I don't know how it comes but it looks like a tag... But I need that.



< LOCATION> \n       < P>Value1< /P> \n < /LOCATION>
< ACCEPTED_VARIANTES VALUE=\"Value2\" />
< PERIOD_DAY> Value3 < /PERIOD_DAY>
< AWARD_CRITERIA_DETAIL > \n       < Value4/> \n       < /AWARD_CRITERIA_DETAIL>

so the result should be:
e.g.
string location = "value1";
string acceptedVariantes = "Value2";
int period = Value3;
string AwarDetail = "Value4";

Upvotes: 0

Views: 7144

Answers (1)

Shimrod
Shimrod

Reputation: 3205

If you use .Net >= 3.5, you can use Linq to SQL to retrieve the values, here is an example:

XElement elem = XElement.Parse("<xml><LOCATION><P>Value1</P></LOCATION><ACCEPTED_VARIANTES VALUE=\"Value2\"/><PERIOD_DAY>Value3</PERIOD_DAY><AWARD_CRITERIA_DETAIL><Value4/></AWARD_CRITERIA_DETAIL></xml>");

var Value1 = elem.Element("LOCATION").Value;
var Value2 = elem.Element("ACCEPTED_VARIANTES").Attribute("VALUE").Value;
var Value3 = elem.Element("PERIOD_DAY").Value;
var Value4 = elem.Element("AWARD_CRITERIA_DETAIL").Element("Value4").Value;

Note: I added <xml>...</xml> tags around the xml string to have it correctly parsing (only 1 root element is always accepted in XML. I assume your DB value is correctly formatted.

On a side note, this code is not protected, it means that if a tag you are looking for (like <LOCATION> for instance) is not present, you'll get an exception (NullReferenceException) when trying to access the Value field.

Instead, you can try this:

var val1 = elem.Element("LOCATION");
var Value1 = val1 != null ? val1.Value : "no data found";

Which will avoid this exception when the tag is not present.

Upvotes: 4

Related Questions