C#以预定义的格式解析XML

时间:2013-11-30 04:07:45

标签: c# xml

以下是我的示例xml文件

<?xml version="1.0"?>
<AAA>
<BBB specName="A" delimiters="," commentChars="#" titleLines="1">
    <DDD name="SSS" col="0"/> 
    <EEE key="XXX">model</EEE> 
</BBB>
<CCC fName="Test" specName="TestRange" >Bol</CCC>
</AAA>

在C#中,我怎么能用以下格式读取这个xml

H=filename.xml


string a = H.root["AAA"].optionset["BBB"].attribute["specName"];
string b=H.root["AAA"].optionset["BBB"].option["EEE"].attribute["key"];
string c=H.root["AAA"].optionset["BBB"].option["EEE"].value;
string d=H.root["AAA"].optionset["CCC"].value;

1 个答案:

答案 0 :(得分:1)

您可以解析它并在之后使用LINQ-to-XML。

您的半伪代码实际上非常接近最终结果。出于这个原因,我冒昧地提供解决方案。

void Main()
{
    string file = "<AAA><BBB specName=\"A\" delimiters=\",\" commentChars=\"#\" titleLines=\"1\"><DDD name=\"SSS\" col=\"0\"/><EEE key=\"XXX\">model</EEE></BBB><CCC fName=\"Test\" specName=\"TestRange\">Bol</CCC></AAA>";
    var doc = XDocument.Parse(file);

    var a = doc.Element("AAA").Element("BBB").Attribute("specName").Value;
    var b = doc.Element("AAA").Element("BBB").Element("EEE").Attribute("key").Value;
    var c = doc.Element("AAA").Element("BBB").Element("EEE").Value;
    var d = doc.Element("AAA").Element("CCC").Value;    


    Console.WriteLine (a);
    Console.WriteLine (b);
    Console.WriteLine (c);
    Console.WriteLine (d);
}

输出:

  

一个
  XXX
  模型
  波尔