I am writing a C# code to parse the following XML doc :
<?xml version="1.0" encoding="utf-8" ?>
<teams>
<team id="1">
<name>RealMadrid</name>
<players>
<player id="1" role="Forward">
<firstname>Cristiano</firstname>
<lastname>Ronaldo</lastname>
<number>7</number>
</player>
<player id="2" role="Forward">
<firstname>Gareth</firstname>
<lastname>Bale</lastname>
<number>11</number>
</player>
<player id="3" role="Midfield">
<firstname>Toni</firstname>
<lastname>Kroos</lastname>
<number>8</number>
</player>
<player id="4" role="Midfield">
<firstname>Luka</firstname>
<lastname>Modric</lastname>
<number>19</number>
</player>
<player id="5" role="Defence">
<firstname>Sergio</firstname>
<lastname>Ramos</lastname>
<number>4</number>
</player>
<player id="6" role="Defence">
<firstname>Raphael</firstname>
<lastname>Varane</lastname>
<number>2</number>
</player>
<player id="7" role="Goalkeeper">
<firstname>Keylor</firstname>
<lastname>Navas</lastname>
<number>1</number>
</player>
</players>
</team>
<team id="2">
<name>Barcelona</name>
<players>
<player id="1" role="Forward">
<firstname>Lionel</firstname>
<lastname>Messi</lastname>
<number>10</number>
</player>
<player id="2" role="Forward">
<firstname>Neymar</firstname>
<lastname>Jr.</lastname>
<number>11</number>
</player>
<player id="3" role="Midfield">
<firstname>Ivan</firstname>
<lastname>Rakitic</lastname>
<number>4</number>
</player>
<player id="4" role="Midfield">
<firstname>Andres</firstname>
<lastname>Iniesta</lastname>
<number>8</number>
</player>
<player id="5" role="Defence">
<firstname>Gerard</firstname>
<lastname>Pique</lastname>
<number>3</number>
</player>
<player id="6" role="Defence">
<firstname>Javier</firstname>
<lastname>Mascherano</lastname>
<number>14</number>
</player>
<player id="7" role="Goalkeeper">
<firstname>Andre</firstname>
<lastname>Ter Stegen</lastname>
<number>1</number>
</player>
</players>
</team>
<team id="3">
<name>Liverpool</name>
<players>
<player id="1" role="Forward">
<firstname>Daniel</firstname>
<lastname>Sturridge</lastname>
<number>15</number>
</player>
<player id="2" role="Forward">
<firstname>Roberto</firstname>
<lastname>Firmino</lastname>
<number>11</number>
</player>
<player id="3" role="Midfield">
<firstname>Philippe</firstname>
<lastname>Coutinho</lastname>
<number>10</number>
</player>
<player id="4" role="Midfield">
<firstname>Adam</firstname>
<lastname>Lallana</lastname>
<number>20</number>
</player>
<player id="5" role="Defence">
<firstname>Joel</firstname>
<lastname>Matip</lastname>
<number>32</number>
</player>
<player id="6" role="Defence">
<firstname>Dejan</firstname>
<lastname>Lovren</lastname>
<number>6</number>
</player>
<player id="7" role="Goalkeeper">
<firstname>Simon</firstname>
<lastname>Mignolet</lastname>
<number>22</number>
</player>
</players>
</team>
</teams>
I want to write the firstname and lastname for players of a specific team.
I wrote the following code :
var realTeam = from db in xelement.Elements("team")
where (string)db.Element("name")=="RealMadrid"
select db;
//Console.WriteLine("Real Madrid");
foreach (var e in realTeam)
{
Console.WriteLine(e);
}
This code is giving all the xml part related to "RealMadrid".
What should I do write on the firstname and lastname of this part?
Any help is appreciated!!
Do it like this:
var xmlContent = "YOUR XML";
var xmlDoc = XDocument.Parse(xmlContent);
var realTeamName = "RealMadrid";
var realTeam = from team in xmlDoc.Elements("teams")
.Descendants("team")
where team.Element("name").Value == realTeamName
select team;
var players = realTeam.Elements("players").Elements(); // get players
foreach (var player in players) // iterate over players
{
Console.WriteLine("First name: " + player.Element("firstname").Value);
Console.WriteLine("Last name: " + player.Element("lastname").Value);
}
So far you've got the team, but now you need to step into the team elements to get the players list and then the single player with firstname, lastname....
As I mentioned in my comment, you're not selecting the players element in your statement. Try the following:
var realTeam = from db in xelement.Elements("team")
where (string)db.Element("name")=="RealMadrid"
select db.Elements("players");
//Console.WriteLine("Real Madrid");
if (realTeam.Count() != 1)
{
//more than 1 team called RealMadrid was found, handle this case here
return;
}
foreach (var e in realTeam.Single())
{
Console.WriteLine("First Name: " + e.Element("firstname").Value); //or e.Element("firstname").ToString()
Console.WriteLine("Last Name: " + e.Element("lastname").Value);
}
Related
I have created two XML files namely XML1 and XML2 Which contain Some Employee ID in this case it is Test1,2,3 apparently
Where I compare both the XML file and find the difference between them
XML1:
<?xml version="1.0"?>
<Employees>
<Employee ID="Test1" />
<Employee ID="Test2" />
<Employee ID="Test3" />
<Employees>
XML2:
<?xml version="1.0"?>
<Employees>
<Employee ID="Testing1" />
<Employee ID="Testing2" />
<Employee ID="Test3" />
<Employees>
C#:
public string CompareXML(XmlTextReader xmlDocument1, XmlTextReader xmlDocument2)
{
var diff = new XmlDiff
{
IgnoreComments = true,
IgnorePI = true,
IgnoreWhitespace = true,
IgnoreChildOrder = true,
Algorithm = XmlDiffAlgorithm.Precise,
};
var wString = new StringWriter();
var xmltw = new XmlTextWriter(wString);
xmltw.Formatting = Formatting.Indented;
var status = diff.Compare(xmlDocument1, xmlDocument2, xmltw);
difference = wString.ToString();
xmltw.Close();
return difference;
}
Basically, I'm comparing two xml files and finding the difference(using Microsoft.XmlDiffPatch), and getting the desired output. But,
What I get
<?xml version="1.0" encoding="utf-16"?>
<xd:xmldiff version="1.0" srcDocHash="11148343190120608020" options="IgnoreChildOrder IgnoreComments IgnorePI IgnoreWhitespace " fragments="no" xmlns:xd="http://schemas.microsoft.com/xmltools/2002/xmldiff">
<xd:node match="2">
<xd:node match="4">
<xd:change match="#ID">Test1</xd:change>
</xd:node>
<xd:node match="1">
<xd:change match="#ID">Test2</xd:change>
</xd:node>
</xd:node>
</xd:xmldiff>
What I need
<?xml version="1.0" encoding="utf-16"?>
<Employees>
<Employee ID="Test1" />
<Employee ID="Test2" />
<Employees>
I have the following XML File:
<order id="1234">
<users>
<user id="102030" nick="nickname" done="false" />
<user id="123456" nick="nickname" done="false" />
</users>
<machines>
<machine id="123" sd="123" ref="" done="false" />
<machine id="456" sd="456" ref="" done="false" />
<machine id="789" sd="789" ref="" done="false" />
</machines>
</order>
I want to delete the user with the id 102030, so the xml looks like this:
<users>
<user id="123456" nick="nickname" done="false" />
</users>
<machines>
<machine id="123" sd="123" ref="" done="false" />
<machine id="456" sd="456" ref="" done="false" />
<machine id="789" sd="789" ref="" done="false" />
</machines>
</order>
This is my code which doesn't work:
XmlDocument doc = XmlDocument.Load(path);
XmlNodeList nodes = doc.GetElementsByTagName("users");
foreach(XmlNode node in nodes){
foreach(XmlAttribute attribute in node.Attributes){
if(attribute.Name== "id" && attribute.Value == "102030"){
node.RemoveAll();
}
}
}
doc.Save(path);
I am a newbie in C# so I need every help!
Thanks in advance, geibi
XmlNode.RemoveAll() does not remove a node. Instead it:
Removes all the child nodes and/or attributes of the current node.
Thus, instead you need to remove the node from its parent:
node.ParentNode.RemoveChild(node);
I have looked at a lot of help files and a lot of similar questions to mine but I am not able to get further than returning the descendant collection.
What I want to achieve is to get an array that contains the values of all the id attributes of the tag elements that have ph or bpt children (not those that have st) in the XPath of xliff\file\header\tag-defs
Here is the xml. I stripped out other tags and it is truncated after the header element, for simplicity:
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns:sdl="http://sdl.com/FileTypes/SdlXliff/1.0" version="1.2" sdl:version="1.0" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file original="\\txl-app1\scncontent\AUDIO\en\Testing\SubtitleXML-FTS\13Mar16_Game.xml" source-language="en-US" datatype="x-sdlfilterframework2" target-language="da-DK">
<header>
<reference>
<internal-file form="base64"></internal-file>
</reference>
<sdl:ref-files>
<sdl:ref-file uid="0" id="http://www.sdl.com/Sdl.FileTypeSupport.Native.Xml/OriginalXmlFile" name="DF44_13Mar16_Speech_BirthdayGame.xml" o-path="\\txl-app1\scncontent\AUDIO\en\Testing\SubtitleXML-FTS\13Mar16_Speech_BirthdayGame.xml" date="04/25/2016 18:55:53" descr="The original XML file." expected-use="Generation" />
</sdl:ref-files>
<file-info xmlns="http://sdl.com/FileTypes/SdlXliff/1.0">
<value key="SDL:FileId">c6550fcb-8e69-428a-a0a8-6447918a97a2</value>
<value key="SDL:CreationDate">04/25/2016 16:16:55</value>
<value key="SDL:OriginalFilePath">\\txl-app1\content\Testing\SubtitleXML-FTS\13Mar16_Game.xml</value>
<value key="SDL:InputFilePath">\\txl-app1\content\en\Testing\SubtitleXML-FTS\13Mar16_Game.xml</value>
<value key="SDL:OriginalEncoding">utf-8</value>
<value key="HasUtf8Bom">true</value>
<value key="IsFragment">false</value>
<value key="SchemaLocation"></value>
<value key="SDL:AutoClonedFlagSupported">True</value>
<value key="xmlDeclaration">true</value>
<value key="SDLWS:AssetId">1489743</value>
<value key="SDLWS:DocId">3043144</value>
<value key="SDLWS:TaskId">1382715</value>
<value key="SDLWS:ScopingMode">0</value>
<value key="SDLWS:CreationDate">2016-04-26T00:16:55Z</value>
<value key="SDLWS:ProjectName">SubtitleXML-FTS_da_DK_20160425_111419</value>
<value key="SDLWS:UserName">BI</value>
<value key="ParagraphTextDirections"></value>
<sniff-info>
<detected-encoding detection-level="Certain" encoding="utf-8" />
<detected-source-lang detection-level="Guess" lang="en-US" />
<props>
<value key="HasUtf8Bom">true</value>
<value key="IsFragment">false</value>
<value key="SchemaLocation"></value>
<value key="xmlDeclaration">true</value>
</props>
</sniff-info>
</file-info>
<sdl:filetype-info>
<sdl:filetype-id>Custom XML v 1.2.0.0 (WS:SubtitleXML-FTS)</sdl:filetype-id>
</sdl:filetype-info>
<fmt-defs xmlns="http://sdl.com/FileTypes/SdlXliff/1.0">
<fmt-def id="1">
<value key="Italic">True</value>
<value key="TextColor">Black</value>
</fmt-def>
</fmt-defs>
<tag-defs xmlns="http://sdl.com/FileTypes/SdlXliff/1.0">
<tag id="7">
<bpt name="i" seg-hint="Include" word-end="false"><i></bpt>
<ept name="i" word-end="false"></i></ept>
<fmt id="1" />
</tag>
<tag id="3">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:00:08 01:05:04:26" WidthAllowed="75"/></ph>
</tag>
<tag id="4">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:05:00 01:05:08:24" WidthAllowed="60"/></ph>
</tag>
<tag id="5">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:08:28 01:05:13:04" WidthAllowed="60"/></ph>
</tag>
<tag id="6">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:13:08 01:05:17:22" WidthAllowed="60"/></ph>
</tag>
<tag id="8">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:17:26 01:05:22:11" WidthAllowed="60"/></ph>
</tag>
<tag id="9">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:21:21 01:05:27:13" WidthAllowed="90"/></ph>
</tag>
<tag id="10">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:27:17 01:05:33:02" WidthAllowed="75"/></ph>
</tag>
<tag id="13">
<ph name="zwnj" word-end="false" seg-hint="Include"><zwnj dir="1" spc="20"/></ph>
</tag>
<tag id="16">
<ph name="Sub" seg-hint="Include"><Sub tc="01:41:20:04 01:41:21:24" WidthAllowed="30"/></ph>
</tag>
<tag id="0">
<st><XMLsubtitlefile"></st>
</tag>
<tag id="1">
<st><Subtitles></st>
</tag>
<tag id="2">
<st><NonVOsubs></st>
</tag>
<tag id="11">
<st></NonVOsubs></st>
</tag>
<tag id="12">
<st><VOsub tc="01:41:01:17 01:41:09:27" WidthAllowed="120"></st>
</tag>
<tag id="14">
<st></VOsub></st>
</tag>
<tag id="15">
<st><NonVOsubs></st>
</tag>
<tag id="17">
<st></NonVOsubs></st>
</tag>
<tag id="18">
<st></Subtitles></st>
</tag>
<tag id="19">
<st></XMLsubtitlefile></st>
</tag>
</tag-defs>
</header>
<body>...
Code-wise I tried different versions, but this is where I am at:
private static XDocument xliff;
public static List<XElement> GetTagArray(string FilePath)
{
xliff = XDocument.Load(Path.GetFullPath(FilePath));
XNamespace ns = "http://sdl.com/FileTypes/SdlXliff/1.0";
var elements = xliff.Descendants().Elements(ns + "tag-defs").Elements().Select(e => e.Elements(ns + "ph")).ToList();
//and here I am stuck as not matter what I do above it returns empty...
}
Thank you for any help in advance.
Untested code, but try something like the following:
XNamespace sdl = #"http://sdl.com/FileTypes/SdlXliff/1.0";
XNamespace ns = #"urn:oasis:names:tc:xliff:document:1.2";
foreach (var tag in xliff.Descendants(sdl + "tag"))
{
foreach (var ph in tag.Elements(sdl + "ph"))
{
// Code here to process
}
}
The solution with help from Jesse Good is:
private static XDocument xliff;
public static int[] GetTagArray(string FilePath)
{
xliff = XDocument.Load(Path.GetFullPath(FilePath));
XNamespace ns = "http://sdl.com/FileTypes/SdlXliff/1.0";
int[] elements = xliff.Descendants().Elements(ns + "tag-defs").Elements(ns + "tag").Elements(ns + "ph").Select(e => Int32.Parse(e.Parent.Attribute("id").Value)).ToArray();
int[] elements2 = xliff.Descendants().Elements(ns + "tag-defs").Elements(ns + "tag").Elements(ns + "bpt").Select(e => Int32.Parse(e.Parent.Attribute("id").Value)).ToArray();
int[] intarray = elements.Concat(elements2).ToArray();
Array.Sort(intarray);
return intarray;
}
I have following XML File:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<T3RecordDocument>
<header type="array">
<charset>utf-8</charset>
<XMLversion>1.0</XMLversion>
<meta type="array">
<title></title>
<description></description>
<notes></notes>
<packager_username>xxxadmin</packager_username>
<packager_name>Firstname</packager_name>
<packager_email>name#domain.com</packager_email>
<TYPO3_version>4.5.26</TYPO3_version>
<created>Thursday 27. June 2013</created>
</meta>
<static_tables index="relStaticTables" type="array">
</static_tables>
<excludeMap type="array">
</excludeMap>
<softrefCfg type="array">
</softrefCfg>
<extensionDependencies type="array">
</extensionDependencies>
<records type="array">
<table index="tx_nfcacedata_lawyer" type="array">
<rec index="678" type="array">
<uid>678</uid>
<pid>233</pid>
<title>Partner & Partner, City</title>
<size>536</size>
<relations index="rels" type="array">
<element index="tx_nfcacedata_county:137" type="array">
<id>137</id>
<table>tx_nfcacedata_county</table>
</element>
</relations>
<softrefs type="array">
</softrefs>
</rec>
<rec index="679" type="array">
<uid>679</uid>
<pid>233</pid>
<title>Name2, City2</title>
<size>530</size>
<relations index="rels" type="array">
<element index="tx_nfcacedata_county:137" type="array">
<id>137</id>
<table>tx_nfcacedata_county</table>
</element>
</relations>
<softrefs type="array">
</softrefs>
</rec>
</table>
</records>
<pid_lookup type="array">
<page_contents index="233" type="array">
<table index="tx_nfcacedata_lawyer" type="array">
<item index="678">1</item>
<item index="679">1</item>
</table>
</page_contents>
</pid_lookup>
</header>
<records type="array">
<tablerow index="tx_nfcacedata_lawyer:678" type="array">
<fieldlist index="data" type="array">
<field index="uid">678</field>
<field index="pid">233</field>
<field index="tstamp">1321450985</field>
<field index="crdate">1250858888</field>
<field index="cruser_id">2</field>
<field index="deleted">0</field>
<field index="name">Partner & Partner</field>
<field index="street">Street 49</field>
<field index="zip">137</field>
<field index="phone">0123 123456</field>
<field index="fax">0123 1234560</field>
<field index="web">www.domain.de</field>
<field index="mail">info#domain.de</field>
<field index="mobile"></field>
<field index="zip_internal">12345</field>
<field index="city_internal">City</field>
<field index="latitude">10.0347062</field>
<field index="longitude">20.7524338</field>
</fieldlist>
<related index="rels" type="array">
<field index="zip" type="array">
<type>db</type>
<relations index="itemArray" type="array">
<element index="0" type="array">
<id>137</id>
<table>tx_nfcacedata_county</table>
</element>
</relations>
</field>
</related>
</tablerow>
<tablerow index="tx_nfcacedata_lawyer:679" type="array">
<fieldlist index="data" type="array">
<field index="uid">679</field>
<field index="pid">233</field>
<field index="tstamp">1257856437</field>
<field index="crdate">1250858888</field>
<field index="cruser_id">2</field>
<field index="deleted">0</field>
<field index="name">Name2</field>
<field index="street">Street 5</field>
<field index="zip">137</field>
<field index="phone">0234 12345678</field>
<field index="fax">0234 123456780</field>
<field index="web">www.domain2.de</field>
<field index="mail">info#domain2.de</field>
<field index="mobile"></field>
<field index="zip_internal">12345</field>
<field index="city_internal">City2</field>
<field index="latitude">10.0523024</field>
<field index="longitude">20.8061242</field>
</fieldlist>
<related index="rels" type="array">
<field index="zip" type="array">
<type>db</type>
<relations index="itemArray" type="array">
<element index="0" type="array">
<id>137</id>
<table>tx_nfcacedata_county</table>
</element>
</relations>
</field>
</related>
</tablerow>
</records>
</T3RecordDocument>
And I am currently parsing it with following code:
XDocument xdoc = XDocument.Parse(XML);
foreach (var descendant in xdoc.Descendants("records").Descendants("tablerow").Descendants("fieldlist"))
{
Lawyer tempLawyer = new Lawyer();
foreach (var item in descendant.Elements())
{
switch (item.Attributes().First().Value)
{
case "name":
tempLawyer.name = item.Value;
break;
case "street":
tempLawyer.street = item.Value;
break;
case "zip_internal":
tempLawyer.zip = item.Value;
break;
case "city_internal":
tempLawyer.city = item.Value;
break;
case "phone":
tempLawyer.phone = item.Value;
break;
case "fax":
tempLawyer.fax = item.Value;
break;
case "web":
tempLawyer.web = item.Value;
break;
case "latitude":
tempLawyer.lat = item.Value;
break;
case "longitude":
tempLawyer.lng = item.Value;
break;
}
}
list_Lawyer.Add(tempLawyer);
}
It's working, but maybe there is a more simpler and faster way to achieve what I want.
Maybe something like this:
var tempList = from element in
xdoc.Descendants("records").Descendants("tablerow").Descendants("fieldlist").Elements()
select new
{
name = (string)element.Attribute("name").Value,
street = (string)element.Attribute("street").Value,
zip = (string)element.Attribute("zip_internal").Value,
city = (string)element.Attribute("city_internal").Value,
phone = (string)element.Attribute("phone").Value,
fax = (string)element.Attribute("fax").Value,
web = (string)element.Attribute("web").Value,
lat = (string)element.Attribute("latitude").Value,
lng = (string)element.Attribute("longitude").Value,
};
This code isn't working because the element's attribute is index="XXXXXX" and not XXXXXX, maybe someone can lead me into the right direction.
from element in xdoc.Descendants("fieldlist")
select new {
Name = element.Elements("field")
.Single(e => e.Attribute("index").Value == "name")
.Value,
...
i am trying to parse an xml element using XMLDocument (DItem >> Title)
below is my code but somehow i am not getting hold of it.... any help?
XmlDocument xmldoc = new XmlDocument();
XmlNamespaceManager xmlns = new XmlNamespaceManager(xdoc.NameTable);
xmlns.AddNamespace("DItems", "http://namespace.xsd");
xmldoc.Load(url);
var title = xmldoc.SelectNodes("content", xmlns);
foreach (XmlNode node in title)
{
string title = node.Attributes["Title"].Value;
//this.ddlTitle.Items.Add(new ListItem(title));
}
here is my XML:
<?xml version='1.0'?>
<root xmlns="http://www.w3.org/2005/Atom">
<title type="text">title</title>
<entry>
<content type="application/xml">
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd">
<CatalogSource Acronym="ABC" OrganizationName="organization name" />
<Item Id="28466" CatalogUrl="url">
<DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title1">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
<entry>
<content type="application/xml">
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd">
<CatalogSource Acronym="ABC" OrganizationName="organization name" />
<Item Id="28466" CatalogUrl="url">
<DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title2">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
<entry>
<content type="application/xml">
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd">
<CatalogSource Acronym="ABC" OrganizationName="organization name" />
<Item Id="28466" CatalogUrl="url">
<DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title3">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
</root>
var xmldoc = new XmlDocument();
var xmlns = new XmlNamespaceManager(xmldoc.NameTable);
xmlns.AddNamespace("DItems", "http://www.namespace.xsd");
xmldoc.Load(url);
var titleNodes = xmldoc.SelectNodes("//DItems:DItem/#Title", xmlns);
var result = titleNodes.Cast<XmlAttribute>().Select(a => a.Value).ToList();
Output (list of objects):
my title1
my title2
my title3