簡體   English   中英

C#-文本框的XML子節點

[英]C# - XML Child Nodes to Text Box

我在將子節點文本放入c#的富文本框中時遇到麻煩。 到目前為止,這是我嘗試過的:

這是XML文件:

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

//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);

這是我得到的錯誤:

System.Xml.dll中發生了類型為'System.Xml.XPath.XPathException'的未處理的異常

附加信息:“ DATA_LIST \\ Customer”具有無效的令牌。

任何幫助都會很棒。

您選擇客戶節點的XPath錯誤,應該是/DATA_LIST/Customer

有關更多詳細信息和示例,請參見XPath語法

您不能在XPath中使用反斜杠。 使用斜杠代替:

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

您可以使用單個XPath來獲取價格:

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

另一個建議是使用LINQ to XML。 您可以按價格獲得價格

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

或沒有XPath:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM