My XML file is:
<?xml version="1.0" encoding="utf-8" ?>
<people>
<person
index="1"
name="Zlecenie numer jeden"
beneficiary="Kowalski"
description="Proste zlecenie jakiejs strony czy cos"
price="800"
deadline="27.12.2013" />
</people>
How can I add to this existing file, something like new record:
<person
index="4"
name="Zlecenie numer cztery"
beneficiary="Kowalski"
description="Proste zlecenie jakiejs strony czy cos"
price="800"
deadline="27.12.2013" />
or remove or if you know how to update existing record then this too. Thanks
Try the next code snippet for adding element into xml. Note that I've used xml as string with escaped characters. You probably have xml file
var str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<people>\r\n<person\r\nindex=\"1\"\r\nname=\"Zlec" +
"enie numer jeden\"\r\nbeneficiary=\"Kowalski\"\r\ndescription=\"Proste zlecenie jakiejs " +
"strony czy cos\"\r\nprice=\"800\"\r\ndeadline=\"27.12.2013\" />\r\n</people>";
var xml = XElement.Parse(str);
var newNode = new XElement("person",
new XAttribute("index", 4),
new XAttribute("name", "Zlecenie numer cztery"),
new XAttribute("beneficiary", "Kowalski"),
new XAttribute("description", "Proste zlecenie jakiejs strony czy cos"),
new XAttribute("price", 800),
new XAttribute("deadline", "27.12.2013"));
xml.Add(newNode);
//you can store whole xml tree in one variable simply by calling ToString on xml
str = xml.Tostring();
Console.WriteLine(str);
Prints:
<people>
<person index="1" name="Zlecenie numer jeden" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
<person index="4" name="Zlecenie numer cztery" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
</people>
XDocument xdoc = XDocument.Load(xmlFileName);
void Update(XDocument xdoc )
{
XElement repser = doc.Root.Element("people").Elements("person").Where(r => (int)r.Attribute("index") = xdoc.index).FirstOrDefault();
if (repser != null)
{
// update
repser.SetAttribute("name", xdoc.name);
repser.SetAttribute("beneficiary", xdoc.beneficiary);
repser.SetAttribute("description", xdoc.description);
repser.SetAttribute("price", xdoc.price);
repser.SetAttribute("deadline", xdoc.deadline);
// and so on
}
else
{
//insert
doc.Root.Element("people").Add
new XElement("person",
new XAttribute("index", xdoc.id),
new XAttribute("name", xdoc.name),
new XAttribute("beneficiary", xdoc.beneficiary),
new XAttribute("description", xdoc.description),
new XAttribute("price", xdoc.price),
new XAttribute("deadline", xdoc.deadline)
// and so on
));
}
}
You can manually plug in the values in the XAttribute values in the else statement for the update.
Related
I'm writing to an XML file from which I'm going to retrieve data later.
Here's how I'm writing to the file.
XNamespace testNM = "urn:lst-emp:emp";
XDocument xDoc;
string path = "project_data.xml";
if (!File.Exists(path))
{
xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(testNM + "Test")
);
}
else
{
xDoc = XDocument.Load(path);
}
var element = new XElement("key",
new XAttribute("name", key),
new XElement("Type", type),
new XElement("Value", value));
xDoc.Element(testNM + "Test").Add(element);
// Save to Disk
xDoc.Save(path);
And this is what my XML file looks like after data is written to it.
<?xml version="1.0" encoding="utf-16"?>
<Test xmlns="urn:lst-emp:emp">
<key name="key2" xmlns="">
<Type>int</Type>
<Value>12312</Value>
</key>
<key name="key3" xmlns="">
<Type>String</Type>
<Value>asdfasd</Value>
</key>
</Test>
Now what would be the simplest way to get the name attribute value (key2 and key3 in this case) along with the Type and Value attribute values.
Load the document;
XDocument doc = XDocument.Load(#"doc.xml");
Loop the key nodes reading what you need;
foreach (var keyNode in doc.Root.Elements("key"))
{
var name = keyNode.Attribute("name");
var type = (string)keyNode.Element("Type"); // or .value to throw if there is no node
...
}
I'm using the following code to write an XML file to disk. If I change the values for each field and re-run the code, the values saved will simply be replaced.
I've looked around here but I see no way to automatically append the new values to the end of the file as a new element and not simply replace everything.
XNamespace empNM = "urn:lst-emp:emp";
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(empNM + "Employees",
new XElement("Employee",
new XComment("Only 3 elements for demo purposes"),
new XElement("EmpId", "5"),
new XElement("Name", "Kimmy"),
new XElement("Sex", "Female")
)));
StringWriter sw = new StringWriter();
XmlWriter xWrite = XmlWriter.Create(sw);
xDoc.Save(xWrite);
xWrite.Close();
// Save to Disk
xDoc.Save("C:\\tempFolder\\test.xml");
Console.WriteLine("Saved");
Also, could someone please explain what "urn:lst-emp:emp"; in the first line does.
void Main()
{
XNamespace empNM = "urn:lst-emp:emp";
XDocument xDoc ;
string path="C:\\tempFolder\\test.xml";
if(!File.Exists(path))
{
xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(empNM + "Employees")
);
}
else
{
xDoc=XDocument.Load(path);
}
var element=new XElement("Employee",
new XComment("Only 3 elements for demo purposes"),
new XElement("EmpId", "5"),
new XElement("Name", "Kimmy"),
new XElement("Sex", "Female"));
xDoc.Element(empNM+"Employees").Add(element);
// Save to Disk
xDoc.Save(path);
Console.WriteLine("Saved");
}
Here is the Xml generated:
<?xml version="1.0" encoding="utf-16"?>
<Employees xmlns="urn:lst-emp:emp">
<Employee xmlns="">
<!--Only 3 elements for demo purposes-->
<EmpId>5</EmpId>
<Name>Kimmy</Name>
<Sex>Female</Sex>
</Employee>
<Employee xmlns="">
<!--Only 3 elements for demo purposes-->
<EmpId>5</EmpId>
<Name>Kimmy</Name>
<Sex>Female</Sex>
</Employee>
</Employees>
I have this xml file called "list.xml".
<?xml version="1.0" encoding="utf-8" ?>
<PeopleList>
<Person>
<First-Name>John</First-Name>
<Last-Name>Sims</Last-Name>
<Address-1>214,NJ Lane</Address-1>
<Address-2>Ney York</Address-2>
<Post-Code>8000</Post-Code>
<City>NJ</City>
</Person>
<Person>
<First-Name>Arya</First-Name>
<Last-Name>Stark</Last-Name>
<Address-1>214,Latin Street</Address-1>
<Address-2>Los Angeles</Address-2>
<Post-Code>302</Post-Code>
<City>CA</City>
</Person>
<Person>
<First-Name>Rick</First-Name>
<Last-Name>Rider</Last-Name>
<Address-1>500,LA Lane</Address-1>
<Address-2>Miami</Address-2>
<Post-Code>768</Post-Code>
<City>LA</City>
</Person>
</PeopleList>
How can I append following data to the above xml?
<Person>
<First-Name>Test User 1</First-Name>
<Last-Name>Test Last Name</Last-Name>
<Address-1>Test add 1</Address-1>
<Address-2>Test add 2</Address-2>
<Post-Code>Test Post code</Post-Code>
<City>Test City</City>
</Person>
Is this the correct way?
XmlDocument xd = new XmlDocument();
xd.Load("list.xml");
XmlNode nl = xd.SelectSingleNode("//Person");
XmlDocument xd2 = new XmlDocument();
xd2.LoadXml("<Person><First-Name>20</First-Name>....</Person>");
XmlNode n = xd.ImportNode(xd2.FirstChild,true);
nl.AppendChild(n);
You can use LINQ to XML
var newElement = new XElement("Person",
new XElement("First-Name", "Test User 1"),
new XElement("Last-Name", "Test Last Name"),
new XElement("Address-1", "Test add 1"),
new XElement("Address-2", "Test add 2"),
new XElement("Post-Code", "Test Post code"),
new XElement("City", "Test City")
);
var xDoc = XDocument.Load("path");
xDoc.Root.Add(newElement);
xDoc.Save(path);
See the documentation for more details: XContainer.Add Method
I want to generate an XML with parameter by parsing the following xml. i am working in c#.net.
<root>
<name1>
<names>
<id>5</id>
<class>space</class>
<from>Germany</from>
<to>France</to>
<through>
<via>
<id>4</id>
<route>Zurich<route>
</via>
<via>
<id>7</id>
<route>Vienna<route>
</via>
</through>
</names>
</name1>
<name2>
<newNames>
<id>8</id>
<path>Road</path>
<dest>USA</dest>
<through>
<route1>
<id>5</id>
<naviagte>Britain</naviagte>
</route1>
<route1>
<id>2</id>
<naviagte>Canada</naviagte>
</route1>
</through>
</newNames>
</name2>
</root>
i want to convert it like following-
<root>
<name1>
<names id = "5";class = "space"; from = "Germany" ; to = "France">
<through>
<via id = "4" ; route = "Zurich">
<via id = "7" ; route = "Vienna">
</through>
</names>
</name1>
<name2>
<newNames id = "8"; path = "Road"; dest = "USA">
<newNames id = "8"; path = "Road"; dest = "USA">
<through>
<route1 = id = "5" ; naviagte = "Britain">
<route1 = id = "2" ; naviagte = "Canada">
</through>
</name2>
</root>
i have tried the following codes.
var doc = XDocument.Load("xml_file.xml");
Console.WriteLine(doc.ToString());
var names = doc.Descendants("name");
var newRootElement = new XElement("root");
foreach (var name in names)
{
var newNameElement = new XElement(name.Name);
foreach (var element in name.Elements())
{
newNameElement.SetAttributeValue(element.Name, element.Value);
}
newRootElement.Add(newNameElement);
}
Console.WriteLine(newRootElement.ToString());
newRootElement.Save("converted_xml_file.xml");
but i can't parse all the nodes. could anyone give me any hints or correction in my codes please ?
I suppose you have closed route tags in your input xml. If so, then you can build new xml by querying original xml and replacing elements with attributes:
var xdoc = XDocument.Load("xml_file.xml");
var root =
new XElement("root",
from name in xdoc.Root.Elements()
select new XElement(name.Name,
from names in name.Elements()
select new XElement(names.Name,
from namesElement in names.Elements()
where namesElement.Name.LocalName != "through"
select new XAttribute(namesElement.Name.LocalName, (string)namesElement),
new XElement("through",
from route in names.Element("through").Elements()
select new XElement(route.Name,
from routeElement in route.Elements()
select new XAttribute(routeElement.Name.LocalName, (string)routeElement))))));
This code produces following xml:
<root>
<name1>
<names id="5" class="space" from="Germany" to="France">
<through>
<via id="4" route="Zurich" />
<via id="7" route="Vienna" />
</through>
</names>
</name1>
<name2>
<newNames id="8" path="Road" dest="USA">
<through>
<route1 id="5" naviagte="Britain" />
<route1 id="2" naviagte="Canada" />
</through>
</newNames>
</name2>
</root>
I have a xml-file:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<level>
<node1 />
<node2 />
<node3 />
</level>
</root>
What is the simplest way to insert values in node1, node2, node3 ?
C#, Visual Studio 2005
Here you go:
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(#"
<root>
<level>
<node1 />
<node2 />
<node3 />
</level>
</root>");
XmlElement node1 = xmldoc.SelectSingleNode("/root/level/node1") as XmlElement;
if (node1 != null)
{
node1.InnerText = "something"; // if you want a text
node1.SetAttribute("attr", "value"); // if you want an attribute
node1.AppendChild(xmldoc.CreateElement("subnode1")); // if you want a subnode
}
//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlFile);
Credit goes to Padrino.
How to change XML Attribute
XElement t = XElement.Load("filePath");
t.Element("level").Element("node1").Value = "";
t.Element("level").Element("node2").Value = "";
t.Element("level").Element("node3").Value = "";
t.Save("filePath");
Use AppendChild method to inser a child inside a node.
yournode.AppendChild(ChildNode);
link text