我有如下的 xml 格式。并尝试从内容、产品名称和产品 ID 中读取元素但无法读取。这是我迄今为止尝试过但没有运气的方法。感谢我的两种方法都不起作用。
<source xml:base="https://google.com/api/v1" xmlns="http://www.w3.org/2005/Atom" >
<id>s1</id>
<value>
<id>value1</id>
<version>1.90</version>
<content type="application/xml">
<x:products>
<n:Productname>3M</n:Productname>
<n:ProductId n:type="Int32">97</n:ProductId>
</x:products>
<x:products>
<n:Productname>HD</n:Productname>
<n:ProductId n:type="Int32">99</n:ProductId>
</x:products>
</content>
</value>
</source>
FileStream fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
XmlDocument xmldoc = new XmlDocument();
XmlNodeList xmlnodecontent;
xmldoc.Load(fs);
xmlnodecontent = xmldoc.GetElementsByTagName("content");
for (int i = 0; i < xmlnodecontent.Count; i++)
{
var innerXml =xmlnodecontent[i].ChildNodes.Item(0).InnerXml;
//Trying to read product here
}
//Second approach
var doc = XDocument.Load(xmlFile);
var units = from u in doc.Descendants("value")
select new
{
Id = (int)u.Element("id"),
content = from entry in doc.Descendants("content")
select new
{
product = (int)u.Element("d:Product"),
}
};
foreach (var unit in units)
{
var id = unit.Id;
var content = unit.content;
}
答案 0 :(得分:0)
我更正了 xml 文件并使用 xml linq (XDocument) 获取值
<source xml:base="https://google.com/api/v1" xmlns="http://www.w3.org/2005/Atom" xmlns:x="abc" xmlns:n="def" >
<id>s1</id>
<value>
<id>value1</id>
<version>1.90</version>
<content type="application/xml">
<x:products>
<n:Productname>3M</n:Productname>
<n:ProductId n:type="Int32">97</n:ProductId>
</x:products>
<x:products>
<n:Productname>HD</n:Productname>
<n:ProductId n:type="Int32">99</n:ProductId>
</x:products>
</content>
</value>
</source>
代码如下:
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);
XElement value = doc.Descendants().Where(x => x.Name.LocalName == "value").FirstOrDefault();
XNamespace ns = value.GetDefaultNamespace();
XNamespace xNs = value.GetNamespaceOfPrefix("x");
XNamespace nNs = value.GetNamespaceOfPrefix("n");
var values = doc.Descendants(ns + "value").Select(x => new
{
id = (string)x.Element(ns + "id"),
products = x.Descendants(xNs + "products").Select(y => new
{
name = (string)y.Element(nNs + "Productname"),
id = (string)y.Element(nNs + "ProductId")
}).ToList()
}).ToList();
}
}
}