C#: nodos secundarios XML a cuadro de texto
Frecuentes
Visto 500 equipos
1
I am having trouble putting a child node text into a rich text box in c#. Here is what I have tried so far:
Aquí está el archivo XML:
<DATA_LIST>
<Customer>
<Full_Name>TEST</Full_Name>
<Total_Price>100</Total_Price>
<Discounts>20</Discounts>
</Customer>
</DATA_LIST>
Código
//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);
Este es el error que obtengo:
An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll
Additional information: 'DATA_LIST\Customer' has an invalid token.
Cualquier ayuda sería genial.
2 Respuestas
1
Your XPath for selecting Customer node is wrong, it should be /DATA_LIST/Customer
Ver Sintaxis XPath para obtener más detalles y ejemplos.
contestado el 28 de mayo de 14 a las 12:05
1
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");
O sin XPath:
int totalPrice = (int)xdoc.Root.Element("Customer").Element("Total_Price");
contestado el 28 de mayo de 14 a las 12:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c# xml xpath or haz tu propia pregunta.
What a stupid mistake. Bit of tweaking and it is working now. Thanks - user3680289