简体   繁体   中英

C# - XML Child Nodes to Text Box

I am having trouble putting a child node text into a rich text box in c#. Here is what I have tried so far:

Here is the XML File:

<DATA_LIST>
  <Customer>
    <Full_Name>TEST</Full_Name>
    <Total_Price>100</Total_Price>
    <Discounts>20</Discounts>
  </Customer>
</DATA_LIST>

Code

//Loads XML Document
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path + "\\Origami - User\\info.xml");

//My attempt at selecting a child node and making it a string
XmlNode xNode = xDoc.SelectSingleNode("DATA_LIST\\Customer");
string TotalPriceString = xNode.SelectSingleNode("Total_Price").InnerText;
txtLogBox.AppendText("test: " + TotalPriceString);

This is the error I get:

An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll

Additional information: 'DATA_LIST\\Customer' has an invalid token.

Any help would be great.

Your XPath for selecting Customer node is wrong, it should be /DATA_LIST/Customer

See XPath Syntax for more details and examples.

You can't use backslash in XPath. Use slash instead:

XmlNode xNode = doc.SelectSingleNode("DATA_LIST/Customer");
string TotalPriceString = xNode.SelectSingleNode("Total_Price").InnerText;

You can use single XPath to get price:

 string totalPrice =  
    doc.SelectSingleNode("DATA_LIST/Customer/Total_Price").InnerText;

Another suggestion is usage of LINQ to XML. You can get price as number

var xdoc = XDocument.Load(path_to_xml);
int totalPrice = (int)xdoc.XPathSelectElement("DATA_LIST/Customer/Total_Price");

Or without XPath:

int totalPrice = (int)xdoc.Root.Element("Customer").Element("Total_Price");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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