2014-04-22 83 views
0

文本框,我已經得到了它具有多個條目的XML文件,每一個看起來像這樣:獲取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#應用程序,它的ID,如CRQ000000003314匹配的字符串。我該如何加載XML,然後將該字符串與事件匹配時,將ID(狀態摘要等)下方的元素返回到單獨的文本框中?

回答

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 
} 
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); 
}