【发布时间】:2021-04-15 17:26:30
【问题描述】:
我的 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;
}
【问题讨论】:
-
发布的 xml 包含命名空间前缀(例如 x:、n:)。所有这些命名空间都必须通过编写例如声明来声明。 xmlns:x="some URI"等。否则xml无效,无法解析(所以
XDocument.Load(xmlFile);会抛出异常)。 -
不幸的是,我无法控制收到的 xml 数据。有没有办法解决这个问题。
-
您的 XML 没有 xml 声明 (
<?xml etc ?>),它只是一个 sn-p。在文件中添加一些文本,包括声明和一些声明了命名空间的元素,然后附加相应的元素结束标记 -
这部分也是无效的 xml
<n:Productname>3M</d:Product>,即使有命名空间 URI 也很难解析
标签: c# xml linq xml-parsing