Hi I need to insert some lines into an xml file and save it how I should do it?
the xml file is
<?xml version="1.0" encoding="utf-8"?>
<Dashboard CurrencyCulture="en-US">
<Title Text="Dashboard" />
<DataConnections>
<DataConnection Name="Database1Connection" ProviderKey="Access2007" ConnectionString="XpoProvider=MSAccess;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Share Deny None;data source=D:\Sina\Desktop\Omid\Database1.accdb;Jet OLEDB:Database Password=;">
<Parameters>
<Parameter Name="database" Value="D:\Sina\Desktop\Omid\Database1.accdb" />
<Parameter Name="read only" Value="1" />
<Parameter Name="generateConnectionHelper" Value="false" />
</Parameters>
</DataConnection>
</DataConnections>
<DataSources>
<DataSource Name="Data Source 1">
<DataProvider DataConnection="Database1Connection" SupportSql="true" />
</DataSource>
<DataSource Name="Query 2" />
</DataSources>
and I need to insert these lines
<Selection>
<Table Name="Query2">
<Columns>
<Column Name="PName" />
<Column Name="Prog" />
<Column Name="RDate" />
</Columns>
</Table>
</Selection>
between
<DataProvider DataConnection="Database1Connection" SupportSql="true">
.
.(here)
</DataProvider>
Here is a complete console application that will take the file you provided as input and build a new file with the nodes added.
NOTE: you will clearly have to make the code more dynamic as this is very static. For example, you would build the Column elements with another list and a loop likely.
class Program
{
static void Main(string[] args)
{
var doc = XDocument.Load("XMLFile1.xml");
var selection = new XElement("Selection");
var table = new XElement("Table");
table.Add(new XAttribute("Name", "Query2"));
var columns = new XElement("Columns");
var column = new XElement("Column");
column.Add(new XAttribute("Name", "PName"));
columns.Add(column);
column = new XElement("Column");
column.Add(new XAttribute("Name", "Prog"));
columns.Add(column);
column = new XElement("Column");
column.Add(new XAttribute("Name", "RDate"));
columns.Add(column);
table.Add(columns);
selection.Add(table);
var dataProvider = doc.Root.Descendants("DataProvider").First();
dataProvider.Add(selection);
doc.Save("XMLFile2.xml");
}
}
The output of the new file looks like this:
<DataSources>
<DataSource Name="Data Source 1">
<DataProvider DataConnection="Database1Connection" SupportSql="true">
<Selection>
<Table Name="Query2">
<Columns>
<Column Name="PName" />
<Column Name="Prog" />
<Column Name="RDate" />
</Columns>
</Table>
</Selection>
</DataProvider>
</DataSource>
<DataSource Name="Query 2" />
</DataSources>
Try this,
XmlDocument document = new XmlDocument();
document.Load(filename);
XmlElement childElement = document.CreateElement("child");
XmlNode parentNode = document.SelectSingleNode("root/firstLevel/parent");
parentNode.AppendChild(childElement);
A quick approach would be:
string file = "XMLFile1.xml";
string text = File.ReadAllText(file);
text = text.Replace("<DataProvider DataConnection=\"Database1Connection\" SupportSql=\"true\" />",
"<DataProvider DataConnection=\"Database1Connection\" SupportSql=\"true\">" +
"<Selection>" +
"<Table Name=\"Query2\">" +
"<Columns>" +
" <Column Name=\"PName\" />" +
"<Column Name=\"Prog\" />" +
"<Column Name=\"RDate\" />" +
"</Columns>" +
"</Table>" +
"</Selection>" +
"</DataProvider> ");
File.WriteAllText(file, text);
Related
I am trying to add new attribute to my xml files in c#. my xml file format is shown below:
<Root MessageOfRoot="Welcome to Xml">
<Header Size="36">
<Parameter Name="ID" Index="0" Value="23" />
<Parameter Name="Name" Index="4" Value="Uncle Bob" />
<Parameter Name="Number" Index="8" Value="4" />
</Header>
<Body Size="0">
<Parameter Index="0" UnitNumber="0" Name="UnitBarcode" Type="Integer" />
<Parameter Index="4" PromotionId="0" Name="PromotionalUnit" Type="Integer" />
</Body>
</Root>
I want to add new attribute my xml file which should be like:
<Root MessageOfRoot="Welcome to Xml">
<Header Size="36" NewAttr="1">
<Parameter Name="ID" Index="0" Value="23" NewAttr="1"/>
<Parameter Name="Name" Index="4" Value="Uncle Bob" NewAttr="1"/>
<Parameter Name="Number" Index="8" Value="4" NewAttr="1"/>
</Header>
<Body Size="0" NewAttr="1">
<Parameter Index="0" UnitNumber="0" Name="UnitBarcode" Type="Integer" NewAttr="1"/>
<Parameter Index="4" PromotionId="0" Name="PromotionalUnit" Type="Integer" NewAttr="1"/>
</Body>
</Root>
To do that i write the following code but i am having problem with adding newAttr to all nodes. How can i add NewAttr to my new xml file?
XmlDocument doc = new XmlDocument();
doc.Load("Path of xml");
XmlAttribute NewAttr = doc.CreateAttribute("NewAttr ");
countAttr.Value = "1";
XmlWriter writer = XmlWriter.Create("output.xml", settings);
You can use the following command to load the XML file:
XDocument doc = XDocument.Load(#"C:\Users\myUser\myFile.xml");
Then you can invoke a function that recursively accesses all nodes of the XML starting from the children nodes of the Root element:
AddNewAttribute(doc.Root.Elements());
The function can be like so:
public static void AddNewAttribute(IEnumerable<XElement> elements)
{
foreach (XElement elm in elements)
{
elm.Add(new XAttribute("newAttr", 1));
AddNewAttribute(elm.Elements());
}
}
Finally, you can save the XML back to the original file using:
doc.Save(#"C:\Users\myUser\myFile.xml");
i want to create some xml with this format
<root>
<columns>
<column name="name1" value="value1" />
<column name="name2" value="value2" />
<column name="name3" value="value3" />
...
</columns>
<rows>
<row name="name1" value="value1" />
<row name="name2" value="value2" />
<row name="name3" value="value3" />
...
</rows>
</root>
so i create a
XElement tree = new XElement("root", new XElement("columns", from c in columns select new XElement("column", c) ...
And the result is
<root>
<columns>
<column>
<column>
<column>
...
</column>
</column>
</columns>
...
</root>
how can i close a node children or something to have what i want??
Following code:
List<KeyValuePair<string, string>> columns = new Dictionary<string,string> {
{"name1", "value1"},
{"name2", "value2"},
{"name3", "value3"}
}.ToList();
XElement tree =
new XElement("root",
new XElement("columns",
from c in columns
select new XElement("column",
new XAttribute("name", c.Key),
new XAttribute("value", c.Value)
)
),
new XElement("rows",
from r in rows // same dictionary as columns
select new XElement("row",
new XAttribute("name", r.Key),
new XAttribute("value", r.Value)
)
)
);
Produces required xml:
<root>
<columns>
<column name="name1" value="value1" />
<column name="name2" value="value2" />
<column name="name3" value="value3" />
</columns>
<rows>
<row name="name1" value="value1" />
<row name="name2" value="value2" />
<row name="name3" value="value3" />
</rows>
</root>
XElement tree = new XElement("root",
new XElement("columns",
from c in columns
select new XElement("column", new XAttribute("name", c.Name,), new XAttribute("value", c.Value))),
new XElement("rows",
from r in rows
select new XElement("row", new XAttribute("name", r.Name,), new XAttribute("value", r.Value))));
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've been messing around with the following code to add each node in an xml fileto a dropdown list but with incorrect results so far.
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(Server.MapPath("~/Upload/" + FileUpload1.FileName));
XmlNodeList question = XmlDoc.GetElementsByTagName("row");
foreach(XmlNode Node in question)
{
string answer = Node["var"].Attributes["name"].InnerText;
string ques = Node["var"].InnerText;
DropDownList1.Items.Add(new ListItem(answer, ques));
}
Here is my xml file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<row>
<var name="Name" value="Garcia" />
<var name=" Surname" value=" Jose" />
<var name=" Country" value=" Cuba" />
<var name=" Job" value="Software Developer" />
<var name=" Cabin" value="345A" />
</row>
<row>
<var name="Name" value="Lenon" />
<var name=" Surname" value="Tim" />
<var name=" Country" value="USA" />
<var name=" Job" value="SoftwareDeveloper" />
<var name=" Cabin" value="444" />
</row>
<row>
<var name="Name" value="Rusell" />
<var name=" Surname" value=" Anthony" />
<var name=" Country" value=" UK" />
<var name=" Job" value="Web Designer" />
<var name=" Cabin" value="345" />
</row>
<row>
<var name="Name" value="Wolf" />
<var name=" Surname" value=" Werner" />
<var name=" Country" value=" Germany" />
<var name=" Job" value="Linux IT" />
<var name=" Cabin" value="234 " />
</row>
</root>
What I need to do is just populate a drop down list with the values Name,Surname,Country,Job and Cabin,so the user can select these values to manipulate the data. I realise with the answer tag im accessing the values also I was trying different things from code ive saw.
The results im getting in my dropdown list from this code is
Name
Name
Name
Name
Im adding the first attribute of each node, but what I need to do is add every value from just one node. NOTE: The xml files il be working with will have different values and names etc so hardcoding is not an option.
If anyone could help Id appreciate it, thank you.
XDocument xml = XDocument.Load(Server.MapPath("~/Upload/" + FileUpload1.FileName));
foreach (var el in xml.Document.Descendants().First().Descendants().First().Descendants())
{
DropDownList1.Items.Add(new ListItem(el.Attribute(XName.Get("name")).Value, Value = el.Value));
}
This is something that you should use DataBinding to accomplish. This blog post has a good example of how you would do this for ASP.NET, which would also apply to WinForms. The key function is:
//populates the dropdownlist from xml file
public void PopulateDDLsFromXMLFile()
{
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/Resources/XMLFile.xml"));
//now define datatext field and datavalue field of dropdownlist
ddlName.DataTextField = "Name";
ddlName.DataValueField = "Name";
...
//now bind the dropdownlist to the dataview
ddlName.DataSource = ds;
ddlName.DataBind();
}
For some more information on databinding, you could read the following: ASP.NET, WinForms, WPF.
I'm not exactly sure what you're doing with the drop down list, but you can use the following code to get to the individual values you want:
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(Server.MapPath("~/Upload/" + FileUpload1.FileName));
string searchpath = "//root//row";
XmlNodeList xmlnodes = XmlDoc.SelectNodes(searchpath);
foreach (XmlNode node in xmlnodes)
{
string name = node.SelectSingleNode("//var[#name='Name']").Attributes["value"].InnerXml;
string surname = node.SelectSingleNode("//var[#name=' Surname']").Attributes["value"].InnerXml;
string Country = node.SelectSingleNode("//var[#name=' Country']").Attributes["value"].InnerXml;
string Job = node.SelectSingleNode("//var[#name=' Job']").Attributes["value"].InnerXml;
string Cabin = node.SelectSingleNode("//var[#name=' Cabin']").Attributes["value"].InnerXml;
}
Are you saying that you want to show Garcia, Lenon,Rusell and Wolf in the ddl? if so, just change your :
Node["var"].Attributes["name"].InnerText;
to
Node["var"].Attributes["value"].Value;
In this WS conumer C# code - , what's the simplest way to Get back all list columns (I only see 10 attributes avaliable) and to filter a a set ID=3. Do I have to qualify all of them in the ndViewFields? where do I place my caml Where? Thanks.
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
ndQueryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>FALSE</DateInUtc><ExpandUserField>FALSE</ExpandUserField>";
//ndViewFields.InnerXml = "<FieldRef Name='Title' /><FieldRef Name='Title' />"; //you don't need to specifically request the 'ID' column since it will be returned regardless
ndViewFields.InnerXml = "<FieldRef Name='Title' />"; //you don't need to specifically request the 'ID' column since it will be returned regardless
ndQuery.InnerXml = "<OrderBy><FieldRef Name='Title'/></OrderBy>";
try
{
XmlNode ndListItems = wList.GetListItems("MyList", string.Empty, ndQuery, ndViewFields,null, ndQueryOptions, null);
foreach (XmlNode node in ndListItems)
{
if (node.Name == "rs:data")
{
for (int f = 0; f < node.ChildNodes.Count; f++)
{
if (node.ChildNodes[f].Name == "z:row")
{
//Add the employee ID to my 'employeeIDs' ArrayList
Titles.Add(node.ChildNodes[f].Attributes["ows_Title"].Value);
Your ndQuery should contain:
<Query>
<Where>
<Eq>
<FieldRef Name="ID" />
<Value Type="Counter">3</Value>
</Eq>
</Where>
</Query>
and ndViewFields should contain:
<ViewFields>
<FieldRef Name="ID" />
<FieldRef Name="Title" />
... all other fields you need
</ViewFields>
Whole XML should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>GUID Or Name</listName>
<query>
<Query xmlns="">
<Where>
<Eq>
<FieldRef Name="ID" />
<Value Type="Counter">1</Value>
</Eq>
</Where>
</Query>
</query>
<viewFields>
<ViewFields xmlns="">
<FieldRef Name="ID" />
<FieldRef Name="Title" />
</ViewFields>
</viewFields>
<queryOptions>
<QueryOptions xmlns="" />
</queryOptions>
</GetListItems>
</soap:Body>
</soap:Envelope>