我有一个这样的 XML 文档:
<magento_api>
<data_item>
<code>400</code>
<message>Attribute weight is not applicable for product type Configurable Product</message>
</data_item>
<data_item>
<code>400</code>
<message>Resource data pre-validation error.</message>
</data_item>
<data_item>
<code>1</code>
<message></message>
</data_item>
<data_item>
<code></code>
<message>No code was given</message>
</data_item>
</magento_api>
我正在尝试迭代每个节点并执行以下操作:
- 扔掉任何空/空白的元素。
- 生成仅包含值的元素的新节点。
- 将生成的文档发送到不同的 Web 服务。
我正在努力的部分是如何遍历每个节点并检查每个元素的空值。
我一直在http://rextester.com/runcode测试此代码,但似乎无法弄清楚:
Console.WriteLine("Querying tree loaded with XElement.Load");
Console.WriteLine("----");
XElement doc = XElement.Parse(@"<magento_api>
<data_item>
<code>400</code>
<message>Attribute weight is not applicable for product type Configurable Product</message>
</data_item>
<data_item>
<code>400</code>
<message>Resource data pre-validation error.</message>
</data_item>
<data_item>
<code>1</code>
<message></message>
</data_item>
<data_item>
<code></code>
<message>No code was given</message>
</data_item>
</magento_api>");
int counter = 1;
IEnumerable<XNode> nodes =
from nd in doc.Nodes()
select nd;
foreach (XNode node in nodes)
{
Console.WriteLine(counter + "-" + node);
IEnumerable<XElement> elements =
from el in node //this is where I've been trying various methods, but no dice.
select el;
foreach (XElement e in elements)
{
Console.WriteLine(counter + "-" + e.Name + "-" + e.Value + "\r\n");
}
counter++;
}
基于上述 XML 输入,我希望得到以下输出:
<magento_api>
<data_item>
<code>400</code>
<message>Attribute weight is not applicable for product type Configurable Product</message>
</data_item>
<data_item>
<code>400</code>
<message>Resource data pre-validation error.</message>
</data_item>
<data_item>
<code>1</code>
</data_item>
<data_item>
<message>No code was given</message>
</data_item>
</magento_api>
我不确定我是否使用正确的方法来迭代节点和元素。