我有以下示例,而c#只是我的草稿。您能告诉我如何调用XML文件并在此处阅读,以便我可以获取值
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>
问题不太清楚,但这就是我认为您想要的:
如果要从XML获得value
,则给定一个option
,这是您可以做到的一种方法:
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;
我更喜欢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>";
}