我相信我把XDocument和XElement方面搞混了。我试图:
简单的结构,称为Rule
public struct Rule
{
public String keyDB;
public String eventLog;
}XML结构:
<?xml version="1.0" encoding="utf-8" ?>
<Error_List>
<Error code="0xC004C003">
<KeyDB>
default key
</KeyDB>
<EventLog>
default event
</EventLog>
</Error>
<Error code="000000000">
<KeyDB>
non-default key
</KeyDB>
<EventLog>
non-default event
</EventLog>
</Error>
</Error_List>设置Rule rule = new Rule();
如果我传递给我的方法"000000000",我希望设置rule.keyDB = "non-default key"和rule.eventLog = "non-default event"。我很确定这是可能的,但我只是把我的变量搞混了。
编辑:
到目前为止,我的代码是不成功和不完整的。我有过
IEnumerable<XElement> query = (from elem in rulesXml.Root.Elements("Error")
where (String)elem.Attribute("code") == this.errorCode.ToString()
select elem);但我不知道从那里往哪里走。
发布于 2013-07-22 16:49:45
一旦掌握了Linq,Linq就非常强大,并且非常容易理解。您可以找到许多关于这两个主题的教程。
以下是你能做的事:
string myCode = "000000000"; // Error Code to find
XDocument xDocument = XDocument.Load("C:/Path to the file.xml"); // Loads the Xml file to a XDocument
Rule rule = (from errorNode in xDocument.Descendants("Error") // Go through Error elements
where errorNode.Attribute("code").Value == myCode // That has the specified code attribute
select new Rule
{
keyDB = errorNode.Element("KeyDB").Value, // Gets the KeyDB element value of the Error node
eventLog = errorNode.Element("EventLog").Value // Gets the EventLog element value of the Error node
}).FirstOrDefault();更新
如果Error元素不能具有代码属性或KeyDB或EventLog属性。使用显式类型转换来检索它们的值。即。而不是写Element.Attribute("...").Value,写(string)Element.Attribute("...") (Element("...")也是一样)
Rule rule = (from errorNode in xDocument.Descendants("Error") // Go through Error elements
where (string)errorNode.Attribute("code") == myCode // That has the specified code attribute
select new Rule
{
keyDB = (string)errorNode.Element("KeyDB"), // Gets the KeyDB element value of the Error node
eventLog = (string)errorNode.Element("EventLog") // Gets the EventLog element value of the Error node
}).FirstOrDefault();发布于 2013-07-22 17:08:09
尝试使用ILookup:
Error code被设置为lookup的键。
public struct Rule
{
public String keyDB;
public String eventLog;
}
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load("src.xml");
ILookup<string, Rule> lookup = xdoc.Descendants("Error").ToLookup(x => x.Attribute("code").Value, x => new Rule() { keyDB = x.Element("KeyDB").Value, eventLog = x.Element("EventLog").Value });
//Perform operation based on the error code from the lookup
Console.Read();
}
}https://stackoverflow.com/questions/17792949
复制相似问题