我有一个这样的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>
我试图遍历每个节点并执行以下操作:
- 扔掉那些空/空的任何元素。
- 生成包含值仅元素新的节点。
- 发送所产生的文档为不同的网络服务。
我挣扎的部分是如何通过每个节点迭代并检查每个元素为空值。
我已经测试了这个代码在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>
我不知道如果我用正确的方法来遍历节点和元素。