我正在从xxx URl读取xml,但由于缺少Root元素,我收到错误.
我读取xml响应的代码如下:
XmlDocument doc = new XmlDocument();
doc.Load("URL from which i am reading xml");
XmlNodeList nodes = doc.GetElementsByTagName("Product");
XmlNode node = null;
foreach (XmlNode n in nodes)
{
}
Run Code Online (Sandbox Code Playgroud)
并且xml响应如下:
<All_Products>
<Product>
<ProductCode>GFT</ProductCode>
<ProductName>Gift Certificate</ProductName>
<ProductDescriptionShort>Give the perfect gift. </ProductDescriptionShort>
<ProductDescription>Give the perfect gift.</ProductDescription>
<ProductNameShort>Gift Certificate</ProductNameShort>
<FreeShippingItem>Y</FreeShippingItem>
<ProductPrice>55.0000</ProductPrice>
<TaxableProduct>Y</TaxableProduct>
</Product>
</All_Products>
Run Code Online (Sandbox Code Playgroud)
你能告诉我哪里出错了.
Phi*_*hil 59
为了防止其他人从Google登陆,我在使用XDocument.Load(Stream)方法时被此错误消息所困扰.
XDocument xDoc = XDocument.Load(xmlStream);
Run Code Online (Sandbox Code Playgroud)
在尝试加载Stream之前,请确保将流位置设置为0(零),这是我总是忽略的一个简单错误!
if (xmlStream.Position > 0)
{
xmlStream.Position = 0;
}
XDocument xDoc = XDocument.Load(xmlStream);
Run Code Online (Sandbox Code Playgroud)
cod*_*der 11
确保XML看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<rootElement>
...
</rootElement>
Run Code Online (Sandbox Code Playgroud)
此外,空白XML文件将返回相同的Root元素缺少异常.每个XML文件都必须有一个根元素/节点,它包含所有其他元素.
嗨,这是奇怪的方式,但尝试一次
XMLDocument.LoadXML(xmlstring)
我尝试使用您的代码和相同的 XML 而不添加任何适用于我的 XML 声明
XmlDocument doc = new XmlDocument();
doc.Load(@"H:\WorkSpace\C#\TestDemos\TestDemos\XMLFile1.xml");
XmlNodeList nodes = doc.GetElementsByTagName("Product");
XmlNode node = null;
foreach (XmlNode n in nodes)
{
Console.WriteLine("HI");
}
Run Code Online (Sandbox Code Playgroud)
正如 Phil 在下面的回答中所述,如果 xmlStream 位置不为零,请将其设置为零。
if (xmlStream.Position > 0)
{
xmlStream.Position = 0;
}
XDocument xDoc = XDocument.Load(xmlStream);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
79389 次 |
最近记录: |