1
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

4

2 回答 2

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);
于 2012-06-21T17:14:25.710 回答
0
XmlNode xnode = doc.SelectSingleNode("Calcs/End");
于 2012-06-21T17:17:01.793 回答