我有一个XML文件,其中有多个条目,每个条目都是这样的:
-<CRQ>
<ID>CRQ000000003314</ID>
<Status>1</Status>
<Summary>complete</Summary>
<Service>Server</Service>
<Impact>3000</Impact>
<Risk>2</Risk>
<Urgency>4000</Urgency>
<Class>4000</Class>
<Environment>1000</Environment>
<Trigger/>
<TriggerID>CP_00</TriggerID>
<Coordinator>user name</Coordinator>
<Desc>ticket description.</Desc>
</CRQ>
我在C#app中有一个与id匹配的字符串,例如CRQ000000003314。当这个字符串在事件上匹配时,我如何能够加载XML然后将id(状态摘要等)下面的元素返回到单独的文本框中?
答案 0 :(得分:1)
您可以使用LINQ to XML
这样获取元素:
var xmlDocument = XDocument.Load("path");
var element = xmlDocument
.Descendants("CRQ")
.FirstOrDefault(x => (string) x.Element("ID") == "CRQ000000003314");
if(element != null)
{
var status = (string)element.Element("Status");
// get other values and display them in the textbox
}
答案 1 :(得分:0)
有几种方法可以做到这一点。您可以使用Linq to XML: http://msdn.microsoft.com/en-us/library/bb387061.aspx
或者您可以使用XMLReader:
http://msdn.microsoft.com/en-us/library/vstudio/system.xml.xmlreader
IT只是通常使用C#进行XML解析:
答案 2 :(得分:0)
这是我的方法:
//Added to set up the sample
var xml = "<root><CRQ><ID>CRQ000000003314</ID><Status>1</Status><Summary>complete</Summary><Service>Server</Service> <Impact>3000</Impact><Risk>2</Risk><Urgency>4000</Urgency><Class>4000</Class><Environment>1000</Environment><Trigger/><TriggerID>CP_00</TriggerID><Coordinator>user name</Coordinator><Desc>ticket description.</Desc></CRQ></root>";
XElement root = XElement.Parse(xml);
//Coded Solution
var value = (from el in root.Elements("CRQ") where el.Element("ID").Value == "CRQ000000003314" select el).FirstOrDefault();
//Testing output
foreach(XElement el in value.Elements()){
Console.WriteLine("Element Name: {0} = {1}",el.Name, el.Value);
}