使用c#读取xml

本文关键字:xml 读取 使用 | 更新日期: 2023-09-27 18:04:28

我需要解析它以获得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"->响应->响应与ID 3->键

使用c#读取xml

您应该阅读有关LINQ to XML的内容。在这里问任何问题之前,你绝对应该做到这一点!

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

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

然后使用标准的LINQ to XML语法进行查询:

var response = (from a in dox.Root.Elements("answerswer")
                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("answerswers/answer[@ID='ANSWER_1']/responses/response[@id='1']");