-3

我需要解析它以获取 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"->responses->response with id 3->key 的回答中获得 elent 的价值

4

1 回答 1

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']");
于 2013-03-17T20:25:06.853 回答