0

我是 xml,c# 的新手。我正在关注本教程:http ://www.dotnetcurry.com/ShowArticle.aspx?ID=564

但我的 xml 文件略有不同。我想在我的 c# 代码中读取的 xml 是这样的:http ://api.nextag.com/buyer/synd.jsp? search=ipod&ver=15&token=AQB7dB $kB8ULvbGT&pid=1807

我试图阅读这个 xml 的代码是:


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

XElement xelement = XElement.Load("http://api.nextag.com/buyer/synd.jsp?search=ipod&ver=15&token=AQB7dB$kB8ULvbGT&pid=1807");
XNamespace nxtg = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-01-11T08:31:30";

IEnumerable<XElement> employees = xelement.Elements();
// Read the entire XML
foreach (var employee in employees)
{
//Console.WriteLine(employee);
//Console.WriteLine(employee.Value);

if (employee.Element(nxtg + "search-category") == null)
continue;
else
Console.WriteLine(employee.Element(nxtg + "search-category").Value);
//Console.WriteLine(employee.Element("EmpId").Value);
}

但没有运气。任何人都可以帮助我。

4

1 回答 1

1

xelement.Elements()将返回根元素的直接子元素。在您的情况下,这将是 elements nxtg:publishernxtg:search-querynxtg:search-category。因此nxtg:search-category是根元素的直接子元素,它也将被选为employee。这就是为什么你在employee. 您应该改为执行以下操作:

// keep in mind, you have incorrect namespace value
XNamespace nxtg = "http://namespace.nextag.com/business-objects";
var searchCategory = xelement.Element(nxtg + "search-category");
var node = searchCategory.Element(nxtg + "node");
var displayName = (string)node.Element(nxtg + "display-name");
var value = (int)node.Element(nxtg + "value");
于 2013-09-13T21:54:36.483 回答