使用c#以ab:tag格式读取XML

时间:2013-09-13 20:28:52

标签: c# xml

我是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);
}

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

1 个答案:

答案 0 :(得分:1)

xelement.Elements()将返回root元素的直接子元素。在您的情况下,元素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");