【发布时间】:2018-11-21 08:51:57
【问题描述】:
我真的需要帮助。我有一个具有以下结构的 xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<Head xmlns="http://www.sample-package.org">
<Number>748</Number>
<Number_confirm>977</Number_confirm>
<Positions>
<Tare_id>2442</Tare_id>
</Positions>
<Positions>
<Product_id>168813</Product_id>
</Positions>
</Head>
我需要在字典中添加键和值(N 和“数字”)、(id 和 Product_id),但需要在没有 linq 的情况下执行此操作,例如:
//load xml from url
doc.Load(temp);
var root = doc.GetElementsByTagName("Head");
var documents = new List<Dictionary<string, object>>();
for (int i = 0; i <root.Count; i++)
{
for (int j = 0; j < root[i].ChildNodes.Count; j++)
{
var element = root[i].ChildNodes[j];
InfoManager.MessageBox("element:{0}", element.Value);
var document = new Dictionary<string, object>();
document.Add("N", element.Attributes.GetNamedItem("Number"));
document.Add("NC", element.Attributes.GetNamedItem("Number_confirm"));
documents.Add("ID",
element.Attributes.GetNamedItem("Product_id"));
documents.Add(document);
}
}
现在 element.Attributes = null,MessageBox 显示元素为空,我看不到 Attributes/Element 并且没有将所有元素添加到字典中。我该如何解决??
【问题讨论】:
-
您要查找的值不是属性。 xml 属性类似于
<tag attribute="value"></tag>。我建议您阅读 XML 和相应的 .net 类。您可能会发现使用 XPath 表达式来获取您正在寻找的信息更容易,因此您可能也想探索一下。