2012-12-19 47 views
0

我有下面的例子,而c#就是我的草稿。你能告訴我如何調用的XML文件,並從中讀到這樣我就可以得到價值xml c#讀寫助手

public static ArrayList GetLocationLiabilityAmount() 
{ 
    ArrayList al = new ArrayList(); 
    string selectedValue = Library.MovieClass.generalLibailityLocationLiability; 
    if (!String.IsNullOrEmpty(selectedValue)) 
    { 
     if (option from xml == selectedValue) 
     { 
      al.Add(minvalue); 
      al.Add(maxvalue); 
     } 
     return al; 
    } 
    else 
    { 
     return null; 
    } 
} 

XML:

<?xml version="1.0" encoding="utf-8" ?> 
<AccidentMedicalCoverage> 
    <coverage option="1" value="10000" showvalue="$10,000 per person"></coverage> 
    <coverage option="2" value="25000" showvalue="$25,000 per person"></coverage> 
    <coverage option="3" value="50000" showvalue="$50,000 per person"></coverage> 
</AccidentMedicalCoverage> 
+0

<?XML版本=「1.0」編碼=「UTF-8」?> c:\\ xmlfile \ coverage.xml – user1883676

+0

什麼是minvalue和maxvalue?我可以在你的xml中看到唯一的'value'屬性。你爲什麼使用'ArrayList'而不是強類型列表? –

回答

1

的問題是不是太清楚,但是這是我想,你希望:

給定一個option如果你想從XML中value,這是一種方式,你可以做到這一點:

XmlDocument xDoc = new XmlDocument(); 
xDoc.Load("c:\\xmlfile\\coverage.xml"); 

// Select the node with option=1 
XmlNode node = xDoc.SelectSingleNode("/AccidentMedicalCoverage/coverage[@option='1']"); 
// Read the value of the Attribute 'value' 
var value = node.Attributes["value"].Value; 
1

我更喜歡linq到Xml。有給定的以獲得如下所示的數據轉換成一個XDocument兩種方式,然後基本查詢到數據

//var xml = File.ReadAllText(@"C:\data.xml"); 
    var xml = GetFile(); 

    //var xDoc = XDocument.Load(@"C:\data.xml"); Alternate 
    var xDoc = XDocument.Parse(xml); 

    var coverages = xDoc.Descendants("coverage"); 

    coverages.Select (cv => cv.Attribute("showvalue").Value) 
      .ToList() 
      .ForEach(showValue => Console.WriteLine (showValue)); 

/* Output 
$10,000 per person 
$25,000 per person 
$50,000 per person 
*/ 

... 

public string GetFile() 
{ 
return @"<?xml version=""1.0"" encoding=""utf-8"" ?> 
<AccidentMedicalCoverage> 
    <coverage option=""1"" value=""10000"" showvalue=""$10,000 per person""></coverage> 
    <coverage option=""2"" value=""25000"" showvalue=""$25,000 per person""></coverage> 
    <coverage option=""3"" value=""50000"" showvalue=""$50,000 per person""></coverage> 
</AccidentMedicalCoverage>"; 
}