Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends,

I need to validate an xml file.
My requirement is Coupon should come first then MaturityDate if its not coming in the specified order its an error,

How can i achieve this? will the xpath works? or any other better alternative.
Please help

C#
var ProjectedIncomePosition = Xele.Descendants("ProjectedIncomePosition");
           foreach(var coupon in ProjectedIncomePosition)
           {
               //XmlDocument xml = new XmlDocument();
               //xml.LoadXml(coupon.ToString());
               //int position =xml.SelectNodes("//Coupon[position()]");

           }


XML
<ProjectedIncomePosition>
		<KeyAcct i:nil="true"/>		
		<Mod1Code>STK</Mod1Code>		
		<ExchangeRate>0</ExchangeRate>
		<CallDate i:nil="true"/>
		<Coupon>0.59</Coupon>		
		<IsExternal>false</IsExternal>
		<MaturityDate/>
		<PreRefundedDate i:nil="true"/>		
		<EstimatedIncome>6.28980</EstimatedIncome>
</ProjectedIncomePosition>
Posted

Try with below code:
C#
string xmlData = @"<projectedincomeposition><keyacct xmlns:h="true" /><mod1code>STK</mod1code><exchangerate>0</exchangerate><coupon>0.59</coupon><isexternal>false</isexternal><maturitydate /></projectedincomeposition>";

// Getting all elements
IEnumerable<XElement> roots = XElement.Parse(xmlData).Elements();

// Coupon index
int coupon = roots.Select((item, index) => new { elementName = item.Name, Index = index }).Where(p => p.elementName == "Coupon").Select(p => p.Index + 1).FirstOrDefault();

// Maturity Date Index
int maturityDate = roots.Select((item, index) => new { elementName = item.Name, Index = index }).Where(p => p.elementName == "MaturityDate").Select(p => p.Index + 1).FirstOrDefault();

if (coupon < maturityDate)
{
	// Correct
}
else
{
	// Incorrect data
}
 
Share this answer
 
v3
Comments
jinesh sam 24-Nov-15 20:11pm    
Thanks Manas :)
What you are trying to do is purely the role of a .xsd xml schema definition, and should be handled this way.

Defining a schema would allow you to clearly and definitely define the valid content of your xml file (including tags, how much of them are allowed, and their respective orders), and to programmatically validate a specific xml file againt the schema.

A few links:
XML Schema (W3C) (Wikipedia)[^]
W3C XML Schema Definition Language (XSD) 1.1[^]
XML Schema Tutorial (w3schools)[^]
 
Share this answer
 
Comments
jinesh sam 24-Nov-15 20:15pm    
Thanks phil:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900