0

I have to read the ordertext ("This is an example text") from this XML File:

<?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:

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:

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

What did I do wrong? Is the XPath incorrect?

I am a C# newbie so I really need every help I can get!

Thanks in advance, geibi

2
  • Please can you show the code you use to write the data. Commented Aug 28, 2018 at 12:23
  • I have tested your xpath here and it seems to be working. Commented Aug 28, 2018 at 12:24

1 Answer 1

2

What you're looking for is 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:

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.