【问题标题】:C# - XML Child Nodes to Text BoxC# - XML 子节点到文本框
【发布时间】:2014-05-28 11:03:13
【问题描述】:

在 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.XPath.XPathException”类型的未处理异常 发生在 System.Xml.dll 中

附加信息:“DATA_LIST\Customer”的令牌无效。

任何帮助都会很棒。

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    你选择客户节点的XPath错误,应该是/DATA_LIST/Customer

    有关更多详细信息和示例,请参阅XPath Syntax。

    【讨论】:

    • 多么愚蠢的错误。稍作调整,它现在正在工作。谢谢
    【解决方案2】:

    您不能在 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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      相关资源
      最近更新 更多