我的XML文件就像..
<?xml version="1.0" encoding="utf-8" ?>
<Controls>
<Control ToValidate="0" ControlID="cmbTrialType" ControlType="FormControl" EngineValueID="" Enabled="0" Visible="1" Single="1" Input="1" Value="Superiority" ListInitValues="Superiority" FormulaEntered="" Caption="" IsValid="1" DecimalPlaces="" />
<Control ToValidate="1" ControlID="cmbTrialType" ControlType="FormControl" EngineValueID="" Enabled="1" Visible="0" Single="1" Input="1" Value="Superiority" ListInitValues="Superiority" FormulaEntered="" Caption="" IsValid="1" DecimalPlaces="" />
</Controls>
我需要读取此xml并执行以下操作
我尝试编写以下功能,但其性能成本更高。
public void LoadXML(String xmlFileName)
{
Stopwatch sw = new Stopwatch();
sw.Start();
string refernceFileName = xmlFileName;
XmlTextReader textReader = new XmlTextReader(refernceFileName);
//int count = 0;
// Read until end of file
while (textReader.Read())
{
XmlNodeType nType = textReader.NodeType;
// if node type is an element
if (nType == XmlNodeType.Element)
{
if (textReader.Name.Equals("Control"))
{
if (textReader.AttributeCount >= 1)
{
String val = string.Empty;
val = textReader.GetAttribute("Visible");
if (!(val == null || val.Equals(string.Empty)))
{
int choice = Int32.Parse(val);
switch (choice)
{
case 0: Console.WriteLine("Visible");
break;
case 1: Console.WriteLine("Not Visible");
break;
}
}
}
}
}
}
sw.Stop();
Console.WriteLine("Elapsed={0}", sw.Elapsed);
//Console.WriteLine(count);
}
答案 0 :(得分:3)
见:
var xml = XElement.Load(@"path\to\your\xml\file");
var elements = xml.Elements("Control").Where(e => e.Attribute("ToValidate") != null);
foreach(var element in elements)
{
var validateAttribute = element.Attribute("ToValidate").Value;
if (validateAttribute == "0")
{
// something if invalid
}
else
{
// something if valid
}
}
如果您的目的只是处理仅存在ToValidate="1"
或ToValidate="0"
的元素。您可以考虑使用它:
var elements = xml.Elements("Control").Where(e => e.Attribute("ToValidate") != null &&
e.Attribute("ToValidate").Value == "1");
答案 1 :(得分:0)
1.执行检查操作
希望你通过课程
答案 2 :(得分:0)
试试这个:
var elements = xml.Elements("Control").Where(
e => e.Attribute("ToValidate") != null
&& e.Attribute("ToValidate").Value == "1"
);