使用C#读取xml

时间:2013-03-17 20:16:29

标签: c# xml

我需要解析它以获取php中的元素我只使用简单的xml文件,但是可以通过c#

    <answers>
<answer ID="START">
<text>VVLV?</text>
<id>0</id>
<responses>

<response id="1">
<key>!1</key>
<product> 123123 </product>
<command>goto ANSWER_1</command>
</response>

<response id="2">
<key>!2</key>
<product> 213sad </product>
<command>goto ANSWER_2</command>
</response>

<response id="3">
<key>!3</key>
<product>dfbdfgsdf </product>
<command>goto ANSWER_3</command>

</response>

</responses>

</answer>

<answer ID="ANSWER_1">
<text>dfbdfgb?</text>
<id>1</id>
<responses>

<response id="1">
<key>!1</key>
<product> 123 </product>
<command>check_product 1 goto ANSWER_9 ANSWER_11</command>
</response>

<response id="2">
<key>!2</key>
<product> 321 </product>
<command>check_product 1 goto ANSWER_9 ANSWER_12</command>
</response>

<response id="3">
<key>!3</key>
<product> asd 3 </product>
<command>check_product 1 goto ANSWER_9 ANSWER_11</command>

</response>

</responses>

</answer>


<answer ID="ANSWER_2">
<text>asd?</text>
<id>2</id>
<responses>

<response id="1">
<key>!1</key>
<product> ads </product>
<command>goto ANSWER_4</command>
</response>

<response id="2">
<key>!2</key>
<product> asdasd </product>
<command>goto ANSWРІER_2</command>
</response>

<response id="3">
<key>!3</key>
<product> dscdsc</product>
<command>goto ANSWER_3</command>

</response>

</responses>

</answer>

<answer ID="ANSWER_3">
<text>asdasd</text>
<password>1</password>
<id>3</id>
<responses>

<response id="1">
<key>!1</key>
<product> asdasd </product>
<command>goto ANSWER_0</command>
</response>

<response id="2">
<key>!2</key>
<product>  </product>
<command>goto ANSWER_2</command>
</response>

<response id="3">
<key>!3</key>
<product> Testqdawd 3 </product>
<command>goto ANSWER_3</command>

</response>

</responses>

</answer>

我如何在C#中解析它,例如我如何通过ID =“START” - &gt;响应 - &gt;回复ID = 3&gt;键

来获取elent的值

1 个答案:

答案 0 :(得分:1)

您应该阅读LINQ to XML。在你在这里提出任何问题之前,你绝对应该这样做!

使用XDocument.Load方法,您可以轻松地将XML加载到XDocument对象:

var dox = XDocument.Load("Input.txt");

然后使用标准LINQ to XML语法查询它:

var response = (from a in dox.Root.Elements("answer")
                where (string)a.Attribute("ID") == "ANSWER_1"
                from r in a.Element("responses").Elements("response")
                where (int)r.Attribute("id") == 1
                select r).FirstOrDefault();

或XPath选择器:

var response = dox.XPathSelectElement("answers/answer[@ID='ANSWER_1']/responses/response[@id='1']");