I have an XML document like this:
<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>
I'm trying to iterate each node and do the following:
- Throw out any elements that are empty/blank.
- Generate new Node with only elements containing values.
- Send the resulting doc to different web service.
The part I'm struggling with is how to iterate through each node and check each element for null values.
I've been testing this code out at http://rextester.com/runcode but can't seem to figure it out:
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++;
}
Based on the above XML input, I'm hoping to get the following output:
<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>
I'm not sure if I'm using the right methods to iterate over the nodes and elements.
from el in node select el
you can just usenode
later... – Hygienic