I have an XML that is laid out to be reformatted into nested HTML table headers. I am working on getting each tier of the XML document into it's own list. For example:
<column name="Total" size="0">
<column name="Users" size="0" />
</column>
<column name="Date" size="0" />
<column name="Unique" size="0">
<column name="Clicks" size="0">
<column name="RC" size="0" />
<column name="CB" size="0" />
</column>
</column>
From this example, columns "Total", "Date", and "Unique" should be in the first list. Columns "Users" and "Clicks" should be in the second list. And, columns "RC" and "CB" should be in the third list. This should be accomplished using recursion to make the method completely dynamic. Any help is greatly appreciated.
Here you go:
XElement root = XElement.Parse(#"
<doc>
<column1>
<column2 />
</column1>
<column3 />
<column4>
<column5>
<column6 />
<column7 />
</column5>
</column4>
</doc>");
List<List<XElement>> outerList = new List<List<XElement>>();
List<XElement> innerList = root.Elements().ToList();
while (innerList.Any())
{
outerList.Add(innerList);
innerList = innerList.SelectMany(element => element.Elements()).ToList();
}
Edit: If you want to strip ancestor XElement instances of their descendants within your list, then you could use the following:
XElement root = XElement.Parse(#"
<table>
<column name=""Total"" size=""0"">
<column name=""Users"" size=""0"" />
</column>
<column name=""Date"" size=""0"" />
<column name=""Unique"" size=""0"">
<column name=""Clicks"" size=""0"">
<column name=""RC"" size=""0"" />
<column name=""CB"" size=""0"" />
</column>
</column>
</table>");
List<List<XElement>> outerList = new List<List<XElement>>();
IEnumerable<XElement> innerList = root.Elements();
while (innerList.Any())
{
outerList.Add(innerList.Select(e => new XElement(e.Name, e.Attributes())).ToList());
innerList = innerList.SelectMany(element => element.Elements());
}
Note: For the record, your intuition that you should use recursion was correct. However, it is also well known that any recursive function can be converted to an iteration, typically by simulating the stack. Sometimes, this leads to bloated code; however, other times, the conversion lends itself naturally. In your case, if you were to recurse, your recursive parameter would have been the immediate children of the set of elements currently being considered – which already happens to be available in innerList, thus allowing us to use the innerList = innerList.<SequenceOperation> trick to substitute the recursion.
Related
I try to get some specific values from an xml config. See example below.
<?xml version="1.0" encoding="utf-8"?>
<ExcelConfig>
<ExcelDocument name="Customer" type="flat">
<IdentityColumn>
<Column name="Id" />
</IdentityColumn>
<Validate>
<Column name="Name" mandatory="true" />
<Column name="FirstName" mandatory="true" />
<OrColumns mandatory="true">
<Column name="PostalCode" mandatory="false" />
<Column name="PostalCode2" mandatory="false" />
</OrColumns>
</Validate>
</ExcelDocument>
<ExcelDocument name="Company" type="flat">
<IdentityColumn>
<Column name="Id" />
</IdentityColumn>
<Validate>
<Column name="Name" mandatory="true" />
<Column name="FirstName" mandatory="true" />
<OrColumns mandatory="true">
<Column name="PostalCode" mandatory="false" />
<Column name="PostalCode2" mandatory="false" />
</OrColumns>
</Validate>
</ExcelDocument>
<ExcelDocument name="SomeOtherType" type="block">
<IdentityBlock>
<Column name="Period" col="A" />
<Column name="Period2" col="B" />
</IdentityBlock>
<Validate>
<Column name="Name" mandatory="true" />
<Column name="FirstName" mandatory="true" />
</Validate>
</ExcelDocument>
</ExcelConfig>
I use the following code to get some information from the excel file.
"ValidationConfiguration" is the string with the previous configuration.
//Get Different NodeTypes of Excel documents
List<XPathNavigator> types = XmlHelper.GetNodeTypes(validationConfiguration, "/ExcelConfig/ExcelDocument");
List<XPathNavigator> flatTypes = XmlHelper.GetNodeTypes(validationConfiguration,
"//ExcelConfig/ExcelDocument[#type='flat']");
List<XPathNavigator> blockTypes = XmlHelper.GetNodeTypes(validationConfiguration,
"//ExcelConfig/ExcelDocument[#type='block']");
//First we check if the file is from the flat type and get the IdentityColumns
List<XPathNavigator> identityColumnsNode = XmlHelper.GetNodeTypes(validationConfiguration, "//ExcelConfig/ExcelDocument[#type='flat']/IdentityColumn");
You can find the XmlHelper class below.
public static class XmlHelper
{
public static List<XPathNavigator> GetNodeTypes(string xmlConfiguration,string xPath)
{
XPathDocument doc = new XPathDocument(new StringReader(xmlConfiguration));
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr = nav.Compile(xPath);
List<XPathNavigator> elements = new List<XPathNavigator>();
foreach (XPathNavigator node in nav.Select(expr))
{
elements.Add(node);
}
return elements;
}
public static List<string> GetIdentityColumnNames(List<XPathNavigator> xPathNavigators)
{
List<string> identityColumns = new List<string>();
foreach (XPathNavigator xPathNavigator in xPathNavigators)
{
foreach (XPathNavigator test in xPathNavigator.Select("//Column"))
{
identityColumns.Add(test.GetAttribute("name", ""));
}
}
return identityColumns;
}
}
Now i want to do the following. I selected the identityColumnsNodes(they contains the IdentityColumn from the exceldocuments that have the flat type).
The i get for al that types the colums. But when i try that, i get all columns back from the whole file. He don't only the items from the node that i use.
foreach (XPathNavigator identityColumNode in identityColumnsNode)
{
List<string> identityColumns = XmlHelper.GetIdentityColumnNames(identityColumnsNode);
}
The second problem/thing i want to do --> the best way to select the right validate node from the specific file. With the identityColumns (that i get back and my list of HeaderRow Cells i know what file it is. But how can i select that validate node?
Or are their better methods to do this stuff?
I have this code. Also here is a sample of the XML. I apologize for any confusion
<object type="node" >
<property name="id" value="1" />
<property name="name" value="ossvc06_node1" />
<property name="port_id" value="50050768014062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768013062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768011062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768012062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="hardware" value="8G4" />
<property name="iscsi_name" value="iqn.1986-03.com.ibm:2145.ossvc06.ossvc06node1" />
<property name="iscsi_alias" value="" />
<property name="failover_active" value="no" />
<property name="failover_name" value="ossvc06_node2" />
<property name="failover_iscsi_name" value="iqn.1986- .com.ibm:2145.ossvc06.ossvc06node2" />
<property name="failover_iscsi_alias" value="" />
<property name="front_panel_id" value="115286" />
</object>
In the input file there are two of these objects of type "Node" each with different values for the property tags.
In this code I am looking for all the objects of type "node" in the incoming XML. There are 2 of them. The 'var nodes' statement evaluates correctly. In the debugger I can see two XElements with what appears to be the proper type and elements in the element list. However, the statement that gets the elements and assigns them to a list has ChildElements from both of the objects of type "node" that are in the XML and I am not sure why.
//load the input file
XDocument xdoc = XDocument.Load(_InputFile);
//get the object of type 'node'
//this code gives the results expected
// in the debugger each XElement appears to have the proper value and childElements
var nodes = from node in xdoc.Descendants("object")
where node.Attribute("type").Value == "node"
select node;
foreach (XElement nodelement in nodes)
{
// problem happens here, the child elements from both nodes get assigned to the list
List<XElement> nodeles = nodelement.Elements().ToList();
Node node = NodeFactory(nodelement);
// now assign the node to the correct IO group
var iogrp = SVCClusters[0].IOGroups.Where(io => io.Name == node.IOGroupName);
if (iogrp.FirstOrDefault().FirstNode == null) { iogrp.FirstOrDefault().FirstNode = node; }
else { iogrp.FirstOrDefault().SecondNode = node; }
}
Can you run this in a console app and tell me what you get
static void Main(string[] args)
{
XDocument xdoc = XDocument.Parse("<root><object type=\"node\" ><property name=\"id\" value=\"1\" /><property name=\"name\" value=\"ossvc06_node1\" /></object><object type=\"node\" ><property name=\"id\" value=\"2\" /><property name=\"name\" value=\"ossvc06_node2\" /></object></root>");
var nodes = xdoc.Descendants("object").Where(node => node.Attribute("type").Value == "node").ToList();
foreach (XElement nodelement in nodes)
{
List<XElement> nodeles = nodelement.Elements().ToList();
foreach (var node in nodeles)
Console.WriteLine(node);
}
}
You should have 4 rows output to the console
Edit---
Original issue was that an XPath expression "//property[#name='port_id']" was being used. This queries from the document root, not from the current node.
Change the XPath to be either "property[#name='port_id'] or ".//property[#name='port_id']"
I'm trying to build a datastructure based on xml content.
The structure looks like that:
Dictionary<string, List<Dictionary<string, string>>>
The XML looks like that:
<Table name="testTable">
<Row>
<Column name="test01" value="2029" />
<Column name="test02" value="2029" />
</Row>
<Row>
<Column name="test01" value="2029" />
<Column name="test02" value="2029" />
</Row>
</Table>
<Table name="testTable01">
<Row>
<Column name="test01" value="2029" />
<Column name="test02" value="2029" />
</Row>
<Row>
<Column name="test01" value="2029" />
<Column name="test02" value="2029" />
</Row>
</Table>
It should result in something like that:
Dictionary<tableName, List<Dictionary<columnName, columnValue>>>
It's no problem to do that with some nested foreach-loops, but I'm searching for a way to do that "in one line" with the LINQ extension methods. How could I do that?
Sounds like you want something like:
var tables = doc.Descendants("Table")
.ToDictionary(t => (string) t.Attribute("name"),
t => ExtractRowsFromTable(t));
...
private static List<Dictionary<string, string>> ExtractRowsFromTable(XElement table)
{
return table.Elements("Row")
.Select(row => row.Elements("Column")
.ToDictionary(c => (string) c.Attribute("name"),
c => (string) c.Attribute("value"))
.ToList();
}
You could do all of this in one line, basically inlining ExtractRowsFromTable - but I really wouldn't.
string xml =
#"<Root>
<Table name=""testTable"">
<Row>
<Column name=""test01"" value=""2029"" />
<Column name=""test02"" value=""2029"" />
</Row>
<Row>
<Column name=""test01"" value=""2029"" />
<Column name=""test02"" value=""2029"" />
</Row>
</Table>
<Table name=""testTable2"">
<Row>
<Column name=""test01"" value=""2029"" />
<Column name=""test02"" value=""2029"" />
</Row>
<Row>
<Column name=""test01"" value=""2029"" />
<Column name=""test02"" value=""2029"" />
</Row>
</Table>
</Root>";
XDocument xDoc = XDocument.Parse(xml);
var table = xDoc
.Descendants("Table")
.Select(t => new
{
Name = t.Attribute("name").Value,
Rows = t.Descendants("Row")
.Select(r=> r.Descendants("Column")
.ToDictionary(c=>c.Attribute("name").Value,
c=>c.Attribute("value").Value))
.ToList()
})
.ToList();
Hey I was wondering if anyone could help to save the value of my xml doc to a c# variable. It is to help with a larger program feature. The XML layout is:
<row>
<var name="bud" value="45" />
<var name="acc" value="345" />
</row>
<row>
<var name="bud" value="45" />
<var name="acc" value="345" />
</row>
I would like to extract the value of bud and store it as a string in my c# code
thanks for any help guys I appreciate it.
XML has to be valid so added a root element.
XML:
<foo>
<row>
<var name="bud" value="45" />
<var name="acc" value="345" />
</row>
<row>
<var name="bud" value="45" />
<var name="acc" value="345" />
</row>
</foo>
Code:
This will return a List with the values of all variables "var" in your XML named "bud" and finally create a comma separated string with all the values.
string xml = "<foo><row><var name=\"bud\" value=\"45\" /><var name=\"acc\" value=\"345\" /></row><row><var name=\"bud\" value=\"45\" /><var name=\"acc\" value=\"345\" /></row></foo>";
XDocument doc = XDocument.Parse(xml);
var budValues =(from c in doc.Descendants("var")
where c.Attribute("name").Value == "bud"
select c.Attribute("value").Value).ToList();
string myBuddy = string.Join(",", budValues);
Your xml is not valid. It requires a single root node.
Here is simple solution using XPath:
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(#"
<dataset><row>
<var name=""bud"" value=""45"" />
<var name=""acc"" value=""345"" />
</row>
<row>
<var name=""bud"" value=""45"" />
<var name=""acc"" value=""345"" />
</row></dataset>");
XmlNode node = xDoc.SelectSingleNode("/dataset/row/var[#name='bud']");
string value = node.Attributes["value"].Value;
This gets only the first of the matches where #name='bud'. Checkout XPath to adjust your result. (it's pretty powerful)
I am trying to make a simple grid view that is binded to a simple xml document but I must be missing something since I am keep getting error message:
The data source for GridView with id
'GridView1' did not have any
properties or attributes from which to
generate columns. Ensure that your
data source has content.
Code
<asp:GridView ID="GridView1" runat="server" DataSourceID="XmlDataSource1">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" />
</Columns>
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server"
DataFile="Notifications.xml" XPath="/data/node"></asp:XmlDataSource>
XML
<?xml version="1.0" encoding="utf-8" ?>
<data>
<node>
<id>1096</id>
<name>About Us</name>
<date>21/12/2009 17:03:43</date>
<user id="1">writer</user>
</node>
<node>
<id>1099</id>
<name>News</name>
<date>21/12/2009 17:03:47</date>
<user id="1">writer</user>
</node>
<node>
<id>1098</id>
<name>Another page</name>
<date>21/12/2009 17:03:52</date>
<user id="1">writer</user>
</node>
</data>
Is it perhaps my xpath that is wrong or am I making something fundamentally wrong here?
There are a number of ways to get this to work:
Use Brian's solution, which is to rewrite the XML to use attributes instead of sub-nodes.
Use an XSLT transform to dynamically convert the child nodes to attributes. See this SO question for an XSLT that can perform that operation.
Load the XML data into a DataSet, which internally does this conversion.
Here's an example of how to do #3:
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/App_Data/mydata.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();
The limitation of this last approach is that you don't get automatic databinding as you would with a data source control. However, since the XmlDataSource is a read-only control anyway, that's not necessarily a serious limitation.
XmlDataSource works with attributes, not child entities. You need to do:
<node id="1096" name="About Us" ../>
Instead of using child elements. Unfortunately it is this way; I really wish it would work with the alternative; I like that approach much better.
try changeing the xpath to
look like XPath="data/node"
Dynamic Databind to XML Document
If your Xml is structured with more info, you will be able to iterate over the structure with more ease, as its easier to identify the exact node your looking for.
We have a web service that returns XML in a row/column structure (similar to your data example above)
For speed Ive copy/pasted our solution, but you should get the gist and be able to hack it to do your thing.
<response xmlns="">
<method name="ExecuteMethod">
<message>Query Successful</message>
<summary success="true" rowcount="2" />
<row>
<column name="ID"><![CDATA[SomeData]]></column>
<column name="NHS_NO"><![CDATA[SomeData]]></column>
<column name="HOSPITALNUMBER"><![CDATA[SomeData]]></column>
<column name="SURNAME"><![CDATA[SomeData]]></column>
<column name="FIRST_FORENAME"><![CDATA[SomeData]]></column>
<column name="TITLE"><![CDATA[SomeData]]></column>
<column name="SEX"><![CDATA[SomeData]]></column>
<column name="DOB">SomeData</column>
<column name="ADDRESS"><![CDATA[SomeData]]></column>
<column name="POSTCODE"><![CDATA[SomeData]]></column>
<column name="DOD" />
</row>
<row>
<column name="ID"><![CDATA[SomeData]]></column>
<column name="NHS_NO"><![CDATA[SomeData]]></column>
<column name="HOSPITALNUMBER"><![CDATA[SomeData]]></column>
<column name="SURNAME"><![CDATA[SomeData]]></column>
<column name="FIRST_FORENAME"><![CDATA[SomeData]]></column>
<column name="TITLE"><![CDATA[SomeData]]></column>
<column name="SEX"><![CDATA[SomeData]]></column>
<column name="DOB">SomeData</column>
<column name="ADDRESS"><![CDATA[SomeData]]></column>
<column name="POSTCODE"><![CDATA[SomeData]]></column>
<column name="DOD" />
</row>
</method>
</response>
Here's the c# implementation
we get the Column names out to pass to the data in to the Gridviews.Datakey names array
we loop over the rows, adding each row to the dataset as we go along
we set the gridviews datasounce to the dataset
we bind()
There's a bit of css and the control instance for your ease of copy/paste in the example below.
//In Code In Front...
Table.DataGridView{float:left; width:100%;}
Table.DataGridView tr{}
Table.DataGridView th{ background-color:Gray; font-weight:bold; color:White;}
Table.DataGridView td{ background-color:White; color:Black; font-weight:normal;}
<asp:GridView ID="DataGridView" runat="server" CssClass="DataGridView" GridLines="Both" Visible="false" />
//In Code Behind...
XmlNode myXmlNodeObject = myXmlDocService.GetData(_xmlDataString);
//Bind To GridView
//Create a DataSet To Bind To
DataSet ds = new DataSet();
ds.Tables.Add("XmlDataSet");
//Get Column Names as String Array
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.LoadXml("<result>" +myXmlNodeObject.ChildNodes.Item(0).ChildNodes.Item(2).ParentNode.InnerXml + "</result>"); //Get Row/Columns
int colCount = myXmlNodeObject.ChildNodes.Item(0).ChildNodes.Item(2).SelectNodes("column").Count;
string[] ColumnNameArray = new string[colCount];
int iterator = 0;
foreach(XmlNode node in myXmlNodeObject.ChildNodes.Item(0).ChildNodes.Item(2).SelectNodes("column"))
{
ColumnNameArray.SetValue(node.Attributes["name"].Value ,iterator);
ds.Tables["XmlDataSet"].Columns.Add(node.Attributes["name"].Value); //Create individual columns in the dataset
iterator++;
}
//Get Data Row By Row to populate the DataSet.Rows
foreach(XmlNode RowNode in XMLDoc.ChildNodes.Item(0).SelectNodes("row"))
{
string[] rowArray = new string[colCount];
int iterator2 = 0;
foreach(XmlNode ColumnNode in RowNode.ChildNodes)
{
rowArray.SetValue(ColumnNode.InnerText, iterator2);
iterator2++;
}
ds.Tables["XmlDataSet"].Rows.Add(rowArray);
}
DataGridView.DataSource = ds.Tables["XmlDataSet"];
DataGridView.DataKeyNames = ColumnNameArray;
DataGridView.DataBind();
DataGridView.Visible = true;