0

我有以下示例,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>
4

2 回答 2

1

I prefer linq to Xml. There are two ways given to get the data into an XDocument shown below and then a basic query into the data

//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>";
}
于 2013-09-17T16:11:58.100 回答
1

这个问题不太清楚,但这是我假设你想要的:

如果option您想value从 XML 中获取,这是您可以做到的一种方法:

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;
于 2013-09-17T16:00:59.297 回答