使用 c# 读取具有 ab:tag 格式的 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);
}

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

xelement.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");

最新更新