简体   繁体   English

使用C#从XML读取数据

[英]Reading data from XML using C#

I have to read the ordertext ("This is an example text") from this XML File: 我必须从以下XML文件中读取订单文本(“这是示例文本”):

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<order id="">
  <users>
    <user id="123456" nick="nick" done="false" />
  </users>
  <machines>
    <machine id="1234" sd="1234" ref="" done="false" />
  </machines>
  <todos />
  <ordertexts>
    <ordertext>This is an example text </ordertext>
  </ordertexts>
</order>

My C# Code looks like this: 我的C#代码如下所示:

XmlDocument xDoc = new XmlDocument();
xDoc.Load(file);
XmlElement node = (XmlElement)xDoc.SelectSingleNode("/order/ordertexts/ordertext");

When I write the selected data in another XML File it looks like this: 当我将所选数据写入另一个XML文件时,它看起来像这样:

<order>
  <oldOrderText>System.Xml.XmlElement</oldOrderText>
</order>

What did I do wrong? 我做错了什么? Is the XPath incorrect? XPath不正确吗?

I am a C# newbie so I really need every help I can get! 我是C#新手,所以我真的需要我能获得的所有帮助!

Thanks in advance, geibi 在此先感谢,geibi

What you're looking for is XmlElement.InnerText . 您正在寻找的是XmlElement.InnerText

When you get the node using this: 当您使用此节点时:

XmlElement node = (XmlElement)xDoc.SelectSingleNode("/order/ordertexts/ordertext");

You still need to use this: 您仍然需要使用以下命令:

string neededText = node.InnerText;

to get the value of that node. 获得该节点的值。

Suppose that you're writing the results in a console application. 假设您正在控制台应用程序中编写结果。 If you try to write the node variable, this way: 如果您尝试编写node变量,可以这样:

Console.WriteLine(node);

Since node is not a string, and it's an XmlElement object, the ToString method of XmlElement is going to be called, which returns the object name, hence your new XML had the result as System.Xml.XmlElement and not the desired text. 由于node不是字符串,而是XmlElement对象,因此将调用XmlElementToString方法,该方法返回对象名称,因此新XML的结果为System.Xml.XmlElement而不是所需的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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