I have an the incoming XML file like this.
<Sport id="23" name="Basketbol">
<Country id="15" name="A.B.D.">
<Tournament id="9" name="Amerikan Basketbol Ligi" type="1" typeDesc="League">
<Season id="95" name="2010/2011">
<Stage id="777" name="2010/2011 Sezonu">
<Team id="104" name="Chicago Bulls" conferenceId="3" conference="Merkez">
<General position="1" totalPlayed="82" won="62" draw="0" lost="20" goalsScored="8087" goalsAgainst="7485" points="144" form="W- W- W- W- W- W" />
<Home position="1" totalPlayed="41" won="36" draw="0" lost="5" goalsScored="4104" goalsAgainst="3683" points="77" />
<Away position="4" totalPlayed="41" won="26" draw="0" lost="15" goalsScored="3983" goalsAgainst="3802" points="67" />
</Team>
I want to save an XML File as below in c#.
<sport>
<id>23></id>
<name>Basketbol</name>
<Country>
<id>15</id>
<name>A.B.D.</name>
LinqToXml: http://msdn.microsoft.com/en-us/library/bb387098.aspx
using System.Xml.Linq;
// [...]
var sourceDoc = XDocument.Load(#"C:\Your\Source\Xml\File.xml");
var sports = sourceDoc.Descendants().Where(s => s.Name == "Sport");
var destDoc = new XDocument(sports.Select(s =>
new XElement("sport",
new XElement("id", s.Attribute("id").Value),
new XElement("name", s.Attribute("name").Value),
new XElement("country",
new XAttribute("id", s.Descendants().Where(c => c.Name == "Country").FirstOrDefault().Attribute("id").Value),
new XAttribute("name", s.Descendants().Where(c => c.Name == "Country").FirstOrDefault().Attribute("name").Value)
)
)
));
destDoc.Save(#"C:\Your\Destination\Xml\File.xml");
Related
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>
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.
i have xml document like this:
<?xml version="1.0" encoding="utf-8" ?>
<demographics>
<country id="1" value="USA">
<state id ="1" value="California">
<city>Long Beach</city>
<city>Los Angeles</city>
<city>San Diego</city>
</state>
<state id ="2" value="Arizona">
<city>Tucson</city>
<city>Phoenix</city>
<city>Tempe</city>
</state>
</country>
<country id="2" value="Mexico">
<state id ="1" value="Baja California">
<city>Tijuana</city>
<city>Rosarito</city>
</state>
</country>
</demographics>
How to select everything starting from demographics node using XML linq queries
something like this:
var node=from c in xmldocument.Descendants("demographics") ??
XDocument xDoc = XDocument.Parse(xml);
var demographics = xDoc
.Descendants("country")
.Select(c => new
{
Country = c.Attribute("value").Value,
Id = c.Attribute("id").Value,
States = c.Descendants("state")
.Select(s => new
{
State = s.Attribute("value").Value,
Id = s.Attribute("id").Value,
Cities = s.Descendants("city").Select(x => x.Value).ToList()
})
.ToList()
})
.ToList();
I want create xml file of this structure:
<Devices>
<Device Number="58" Name="Default Device" >
<Functions>
<Function Number="1" Name="Default func" />
<Function Number="2" Name="Default func2" />
<Function Number="..." Name="...." />
</Functions>
</Device>
</Devices>
Here's my code:
document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions")));
Each object "device" have List<> of "functions", how can i add "functions" to xml???
Each object "device" have List<> of "functions", how can i add "functions" to xml???
Really easily - LINQ to XML makes this a doddle:
document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions",
functions.Select(f =>
new XElement("Function",
new XAttribute("Number", f.ID),
new XAttribute("Name", f.Name))))));
In other words, you just project your List<Function> to an IEnumerable<XElement> using Select, and the XElement constructor does the rest.
document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions", from f in functions select new XElement("Function", new XAttribute("Number", f.Number), new XAttribute("Name", f.Name)))));
functions would be your list of functions.
XML:
<Questions>
<Question>
<Id>1</Id>
<Text>aaa</Text>
<Reserver />
</Question>
<Question>
<Id>2</Id>
<Text>bbb</Text>
<Reserver />
</Question>
</Questions>
How can insert new Question using LINQ like this:
<Question>
<Id>3</Id>
<Text>ccc</Text>
<Reserver />
</Question>
XDocument doc = XDocument.Parse("<Questions>...</Questions>");
doc.Root.Add(
new XElement("Question",
new XElement("Id", 3),
new XElement("Text", "ccc"),
new XElement("Reserver"))
);
You can create a new element like this:
var newElem = new XElement("Question",
new XElement("Id", 3),
...
);
xdoc.Root.Add(newElem);