xml file parsing
How can I add/alter to my code so once if extracts out the values of the max/min it compare the extracted value to a set value and writes out pass/fail. For example: xmax extracts out and it is 280 and I have a condition in my code saying that xmax needs to be less than 275 so write out fail. This needs to be done for each max/min.Any Ideas...? I used linq to xml to parse but is their a better way?
var qu开发者_开发百科ery = from file in fileEntries
let doc = XDocument.Load(file)
let x = doc.Descendants("XAxisCalib").Single()
let y = doc.Descendants("YAxisCalib").Single()
let z = doc.Descendants("ZAxisCalib").Single()
select new
{
XMax = x.Element("Max").Value,
XMin = x.Element("Min").Value,
YMax = y.Element("Max").Value,
YMin = y.Element("Min").Value,
ZMax = z.Element("Max").Value,
ZMin = z.Element("Min").Value
};
Something like this maybe?
var results = from item in query
select new
{
XMaxResult = item.XMax < 275 ? "pass" : "fail",
...
};
I'd use an XML schema for this.
It will let you build your C# so that it takes just a few lines of code to check the document both for structural correctness, and semantic correctness. It is also something you can publish separately from your app so that users can understand how documents should be laid out. Some XML editors support schemas, too, so they might get some sort of automatic syntactical support/checking in their editor.
Here is how you would check a maximum value in an XSD schema:
http://www.w3schools.com/schema/schema_facets.asp
...
<xs:element name="Max">
<xs:simpleType>
<xs:restriction base="xs:integer">
<!-- Must be less than 275 -->
<xs:maxInclusive value="274"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
...
You can create an Extension Method to check the value
public static class Test {
static int check(this XElement element)
{
if(element.Value < 100 || element.Value > 275)
{
throw new Exception();
}
return element.Value;
}
}
Then you can do
select new
{
XMax = x.Element("Max").Check(),
XMin = x.Element("Min").Check(),
YMax = y.Element("Max").Check(),
YMin = y.Element("Min").Check(),
ZMax = z.Element("Max").Check(),
ZMin = z.Element("Min").Check()
};
精彩评论