下面是我需要处理的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<shipment-info xmlns="http://www.canadapost.ca/ws/shipment-v8">
<shipment-id>11111111</shipment-id>
<shipment-status>created</shipment-status>
<tracking-pin>123456789012</tracking-pin>
<links>
<link rel="self" href="https://xxx" media-type="application/vnd.cpc.shipment-v8+xml"/>
<link rel="details" href="https://xxx" media-type="application/vnd.cpc.shipment-v8+xml"/>
<link rel="group" href="https://xxx" media-type="application/vnd.cpc.shipment-v8+xml"/>
<link rel="price" href="https://xxx" media-type="application/vnd.cpc.shipment-v8+xml"/>
<link rel="label" href="https://xxx" media-type="application/pdf" index="0"/>
</links>
</shipment-info>我想要得到追踪针的值,下面是这样做的代码:
// xml text
string xml = (xml source above)
// load xml
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// getting tracking pin
XmlNode node = doc.SelectSingleNode("/shipment-info"); // problem start here -> node return null
Console.WriteLine(node["tracking-pin"].InnerText);
// getting self and label links
node = doc.SelectSingleNode("/shipment-info/links");
foreach (XmlNode child in node)
{
if (child.Attributes["rel"].Value == "self")
Console.WriteLine(child.Attributes["href"].Value);
else if (child.Attributes["rel"].Value == "label")
Console.WriteLine(child.Attributes["href"].Value);
}
Console.ReadLine();但是,对于选择“/ selecting”,它返回一个空值,我不知道为什么会出现这种情况。怎么处理?
发布于 2016-04-04 17:29:06
您有一个名称空间,需要对其进行说明:
// load xml
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);
//Add the namespaces used in books.xml to the XmlNamespaceManager.
xmlnsManager.AddNamespace("veeeight", "http://www.canadapost.ca/ws/shipment-v8");
// getting tracking pin
XmlNode node = doc.SelectSingleNode("//veeeight:shipment-info", xmlnsManager); // problem start here -> node return null见:
发布于 2016-04-04 17:24:01
您有一个名称空间问题。试试这个XML解决方案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns = ((XElement)(doc.FirstNode)).Name.Namespace;
string tracking_pin = doc.Descendants(ns + "tracking-pin").FirstOrDefault().Value;
}
}
}发布于 2016-04-04 17:29:01
将其添加到代码中
XmlNode root = doc.DocumentElement;https://stackoverflow.com/questions/36408901
复制相似问题