【问题标题】:XmlNode keeps saying there is no nodes but there isXmlNode 一直说没有节点但有
【发布时间】:2012-06-21 17:09:21
【问题描述】:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Plus_Click(object sender, EventArgs e)
        {
            string FValue = id.Text;
            string SValue = id2.Text;
            string ending;
            string url = "http://localhost:56254/api/add?id=" + FValue + "&id2=" + SValue;
            WebClient client = new WebClient();
            client.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";
            client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            string data = client.DownloadString(url);
            XmlDocument xdoc = new XmlDocument();

            xdoc.LoadXml(data);
   -->      XmlNode xnode = xdoc.SelectSingleNode("End");
            ending = xnode.InnerText;
            Answer.Text = ending;
        }
    }
}

这是我的代码,它在结束时一直给我一个空值,如果我在箭头处放置一个断路器,它会告诉我 count = 0。这是我的 xml:

- <Calcs xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Calculator.Models">
              <End>10</End> 
              <FValue>5</FValue> 
              <SValue>5</SValue> 
  </Calcs>

当我打电话给 End 时,它一直告诉我没有节点被称为 End.... 并且一直给我 null 我做错了什么吗? http://i45.tinypic.com/24cgkld.png

【问题讨论】:

  • 确保你的 xdoc 有 xml 数据
  • 它确实有所有数据和第一个孩子 id "Calcs" 然后第一个孩子是 End 之后所以 xdoc 有一切。

标签: c# xml get


【解决方案1】:

SelectSingleNode 方法需要一个 XPath 表达式,试试这个:

XmlNode xnode = xdoc.SelectSingleNode("//End");

编辑:这是一个命名空间问题,请尝试以下操作:

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("cm", "http://schemas.datacontract.org/2004/07/Calculator.Models");

XmlNode xnode = xdoc.SelectSingleNode("//cm:End", nsmgr);

【讨论】:

  • 这对我有用,你的 xdoc 必须是空的,否则你没有给我们完整的 XML。
  • 不,它仍然不起作用我可以从屏幕截图中发布我的确切值我会在一秒钟内发布图片
  • 非常感谢您刚刚完成我的申请非常感谢:D
  • 嘿,你能解释一下厘米是什么吗?
  • 它只是命名空间的别名,你可以放任何东西而不是“cm”。
【解决方案2】:
XmlNode xnode = doc.SelectSingleNode("Calcs/End");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2012-12-03
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 2023-04-07
    相关资源
    最近更新 更多