简体   繁体   中英

xml c# read and write helper

I have the following examples, and the c# is just my draft. Can you show me how to call the xml file and read there so I can get the value

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>

The question is not too clear but this is what I assume you want:

Given an option if you want to get the value from the XML this is one way you can do it:

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM