I have an XML with this structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Dossiers xmlns:ns2="http://www.dat.de/vxs" source="SD3" type="completeEvaluation">
<ns2:Dossier>
<ns2:Vehicle>
<ns2:VehicleIdentNumber>aaaaaaaaaa</ns2:VehicleIdentNumber>
<ns2:Equipment>
<ns2:OriginalEquipmentValueGross origin="dat">16206.00</ns2:OriginalEquipmentValueGross>
<ns2:SeriesEquipment>
<ns2:EquipmentPosition>
<ns2:DatEquipmentId>15201</ns2:DatEquipmentId>
<ns2:Description>lorem ipsum</ns2:Description>
</ns2:EquipmentPosition>
<ns2:EquipmentPosition>
<ns2:DatEquipmentId>17602</ns2:DatEquipmentId>
<ns2:Description>lorem ipsum</ns2:Description>
</ns2:EquipmentPosition>
...
</ns2:SeriesEquipment>
</ns2:Vehicle>
<ns2:Vehicle>
....
</ns2:Vehicle>
</ns2:Dossier>
</ns2:Dossiers>
With this code I have obtained the ns2:VehicleIdentNumber value:
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlFileContent);
var xmlNodeList = xml.GetElementsByTagName("ns2:Vehicle");
foreach (XmlElement xmlElement in xmlNodeList)
{
var telaio = xmlElement["ns2:VehicleIdentNumber"];
}
but how can I get ns2:OriginalEquipmentValueGross value and ns2:Description value?
Using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace ns2 = root.GetNamespaceOfPrefix("ns2");
var results = doc.Descendants(ns2 + "Vehicle").Select(x => new
{
vehicleIdentNumber = (string)x.Element(ns2 + "VehicleIdentNumber"),
originalEquipmentValueGross = (string)x.Descendants(ns2 + "OriginalEquipmentValueGross").FirstOrDefault()
}).ToList();
}
}
}
It should be more or less the same of what you already have:
var xmlNodeList = xml.GetElementsByTagName("ns2:Vehicle");
foreach (XmlElement xmlElement in xmlNodeList)
{
var telaio = xmlElement["ns2:VehicleIdentNumber"];
var equipment = xmlElement["ns2:Equipment"];
var originalEquipmentValueGross = equipment["ns2:OriginalEquipmentValueGross"].InnerText;
foreach (XmlElement equipmentPosition in equipment["ns2:SeriesEquipment"].GetElementsByTagName("ns2:EquipmentPosition"))
{
var description = equipmentPosition["ns2:Description"].InnerText;
}
}
Related
I have the following xml
<lists>
<list Group="3">More_lists_go_here</list>
</lists>
What I want is both the list element value which is More_lists_go_here and the Group attribute value which is 3.
What I have tried so far is
XmlDocument doc = new XmlDocument();
doc.LoadXml("<list Group=\"3\">More_lists_go_here</list>");
XmlElement root = doc.DocumentElement;
string value = root.Descendants("lists").Elements("list").Select(x => (string)x.Attribute("Group")).ToList();
what that gets me is
value = 3
what I want is both 3 and More_lists_go_here for string value
Use xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication40
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string input = "<lists><list Group=\"3\">More_lists_go_here</list></lists>";
XDocument doc = XDocument.Parse(input);
var results = doc.Descendants("list").Select(x => new { group = (string)x.Attribute("Group"), value = (string)x }).ToList();
}
}
}
I have the following XML and i want to convert the contents to something along the lines of the following format.
PatientId: 123455, IdScheme: Test ....
<?xml version="1.0"?>
<gls:TheDocument xmlns:pbr="http://www.something.com"
xmlns:gls="http://www.testsomething.com"
xmlns:cnr="http://www.organisation.com"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="2.8">
<gls:PatientDem>
<cnr:PatientId>
<cnr:IdValue>123455</cnr:IdValue>
<cnr:IdScheme>TEST</cnr:IdScheme>
<cnr:IdType>PRN</cnr:IdType>
</cnr:PatientId>
<cnr:PatientName>
<cnr:Name>
<cnr:Title>Mr</cnr:Title>
<cnr:GivenName>Joe</cnr:GivenName>
<cnr:FamilyName>Wood</cnr:FamilyName>
</cnr:Name>
<cnr:NameType>Current Name</cnr:NameType>
</cnr:PatientName>
<cnr:PatientAddress>
<cnr:Address>
<cnr:AddressLine>57 High Street</cnr:AddressLine>
<cnr:AddressLine>London</cnr:AddressLine>
</cnr:Address>
<cnr:PostCode>WC1E 7HU</cnr:PostCode>
<cnr:AddressType>Current Residence</cnr:AddressType>
</cnr:PatientAddress>
<cnr:DateOfBirth>1969-11-02</cnr:DateOfBirth>
<cnr:Sex>M</cnr:Sex>
</gls:PatientDem>
<pbr:PatientAdminRef>
<pbr:Referrer>
<pbr:RefGP>
<cnr:GpcpName>
<cnr:FullName>DR SMITH</cnr:FullName>
</cnr:GpcpName>
<cnr:TheOrganisation>
<cnr:OrganisationId>
<cnr:IdValue>52522</cnr:IdValue>
<cnr:IdScheme>PracticeID</cnr:IdScheme>
<cnr:IdType>Healthcare Organisation</cnr:IdType>
</cnr:OrganisationId>
<cnr:OrganisationName>National Health
Service</cnr:OrganisationName>
<cnr:OrganisationAddress>
<cnr:TheAddress>
<cnr:AddressLine1>Centre House</cnr:AddressLine1>
<cnr:AddressLine2>799 Chichester
Street</cnr:AddressLine2>
<cnr:AddressLine3>London</cnr:AddressLine3>
</cnr:TheAddress>
<cnr:AddressType>Practice Address</cnr:AddressType>
</cnr:OrganisationAddress>
<cnr:OrganisationTelecom>
<cnr:TelephoneNumber>016190542350</cnr:TelephoneNumber>
<cnr:TeleType>Voice</cnr:TeleType>
</cnr:OrganisationTelecom>
</cnr:TheOrganisation>
</pbr:RefGP>
</pbr:Referrer>
</pbr:PatientAdminRef>
</gls:TheDocument>
So is it possible to do this? I had a go at doing this but I know for a fact i am doing it wrong as it cannot produce the result i want so any help will be much appreciated:
C# Code
XDocument doc = XDocument.Parse(xml);
XElement root = doc.Root;
XNamespace glsNs = root.GetNamespaceOfPrefix("gls");
XNamespace cnrNS = root.GetNamespaceOfPrefix("cnr");
XNamespace pbrNS = root.GetNamespaceOfPrefix("pbr");
var output = new StringBuilder();
foreach (var result in doc.Descendants(gls + "PatientDem").Select(x => new {
Key = (string)x.Name.LocalName,
Value = x.Value
}))
{
output.AppendLine($"{result.key} : {result.value}");
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication108
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace cnrNs = root.GetNamespaceOfPrefix("cnr");
var results = doc.Descendants(cnrNs + "PatientId").Select(x => new {
value = (string)x.Element(cnrNs + "IdValue"),
scheme = (string)x.Element(cnrNs + "IdScheme")
}).ToList();
}
}
}
I have a GML string:
<gml:LineString><gml:coordinates>1537544.53,452064.2 1537541.719999999,452062.3099999999 1537523.159999999,452044.55 1537544.53,452064.2</gml:coordinates></gml:LineString>
Now i want to convert it to xml document
var t = "<gml:LineString>....</gml:LineString>";
XmlDocument doc = new XmlDocument();
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("gml", "http://www.opengis.net/gml");
doc.Load(t);
But on doc.Load(t); got exception:
System.Xml.XmlException: "Prefix "gml" undeclared."
How to add namespace and read read line?
UPDATE
I'd fix code based on #jdweng answer:
XmlReaderSettings settings = new XmlReaderSettings { NameTable = new NameTable() };
var nsmgr = new XmlNamespaceManager(settings.NameTable);
nsmgr.AddNamespace("gml", "http://www.opengis.net/gml");
XmlParserContext context = new XmlParserContext(null, nsmgr, "", XmlSpace.Default);
XmlReader reader = XmlReader.Create(new StringReader(gmlString), settings, context);
if (gmlString.StartsWith("<gml:Polygon>"))
{
XmlSerializer serializer = new XmlSerializer(typeof(PolygonType));
return new tGeoLPT { Item = (PolygonType)serializer.Deserialize(reader)
};
}
Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string coordinates = "1537544.53,452064.2 1537541.719999999,452062.3099999999 1537523.159999999,452044.55 1537544.53,452064.2";
string line = "<gml:LineString xmlns:gml=\"http://www.opengis.net/gml\"></gml:LineString>";
XElement xLine = XElement.Parse(line);
XNamespace ns = xLine.GetNamespaceOfPrefix("gml");
xLine.Add(new XElement(ns + "coordinates"), coordinates);
}
}
}
I have the following XML
<User
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models">
<Game_ID>3</Game_ID>
<UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>
<UserName>tony2</UserName>
<User_ID>16</User_ID>
</User>
Using C# I am loading this into an XMLDocument, How do I retrieve the UserGUID value?
Leveraging System.Xml.Linq you could do
string xml = "..."; // your inline XML
var doc = System.Xml.Linq.XDocument.Parse(xml);
or
string xmlFile = "..."; // your XML filename
var doc = System.Xml.Linq.XDocument.Load(xmlFile);
and then, to get the UserGUID
var userGuid = doc.Descendants().Where(x=>x.Name.LocalName == "UserGUID").First().Value;
This will work for you.
string xml = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models\">" +
"<Game_ID>3</Game_ID>" +
"<UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>" +
"<UserName>tony2</UserName>" +
"<User_ID>16</User_ID>" +
"</User>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var id = doc.GetElementsByTagName("UserGUID")[0].InnerText;
You need to use the namespace. I often use mipnw approach (probably stole idea from one of my postings). See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement user = doc.Root;
XNamespace ns = user.GetDefaultNamespace();
string UserGUID = (string)user.Element(ns + "UserGUID");
}
}
}
I'm trying to create a program having the following steps:
1) Get all xml files from a user given path
2) Open each of the files (if any) and search for nodes <institution> where it is in the format <funding-source><institution-wrap><institution>...</institution></institution-wrap></funding-source>
3) Get the value of the nodes <institution> and search the exact value in the database xml inside the nodes <skosxl:literalForm xml:lang="...">
4) If found, get the attribute value of its parent node <skos:Concept rdf:about="..."> minus the string http://dx.doi.org/
5) Add a node <institution-id institution-id-type="fundref"> in the xml file after the <institution> node with the value like <funding-source><institution-wrap><institution>...</institution><institution-id institution-id-type="fundref">VALUE of the rdf:about attribute</institution-id></institution-wrap></funding-source>
Here is a sample input file and the desired output for that file.
What I have tried:
string pathToUpdatedFile = #"D:\test\Jobs";
var files=Directory.GetFiles(pathToUpdatedFile,"*.xml");
foreach (var file in files)
{
var fundingDoc = XDocument.Load(#"D:\test\database.xml");
XNamespace rdf=XNamespace.Get("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
XNamespace skosxl = XNamespace.Get("http://www.w3.org/2008/05/skos-xl#");
XNamespace skos=XNamespace.Get("http://www.w3.org/2004/02/skos/core#");
var targetAtt = fundingDoc.Descendants(skos+"Concept").Elements(skosxl+"prefLabel")
.ToLookup(s => (string)s.Element(skosxl+"literalForm"), s => (string)s.Parent.Attribute(rdf+"about"));
XDocument outDoc = XDocument.Parse(File.ReadAllText(file),LoadOptions.PreserveWhitespace);
foreach (var f in outDoc.Descendants("funding-source").Elements("institution-wrap"))
{
if (f.Element("institution-id") == null)
{
var name = (string)f.Element("institution");
var x = targetAtt[name].FirstOrDefault(); // just take the first one
if (x != null)
f.Add(new XElement("institution-id", new XAttribute("institution-id-type","fundref"),x.Substring(#"http://dx.doi.org/".Length)));
}
outDoc.Save(file);
}
Console.ReadLine();
But it is not working...Can somebody help...
See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApplication31
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
const string DATABASE = #"c:\temp\test1.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement article = doc.Root;
XNamespace ns = article.GetDefaultNamespace();
XDocument docDatabase = XDocument.Load(DATABASE);
XElement rdf = docDatabase.Root;
XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");
List<XElement> prefLabels = rdf.Descendants(nsSkosxl + "prefLabel").ToList();
Dictionary<string, List<string>> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Element(nsSkosxl + "Label").Attribute(nsRdf + "about"))
.ToDictionary(x => x.Key, y => y.ToList());
List<XElement> fundingSources = article.Descendants(ns + "funding-source").ToList();
foreach (XElement fundingSource in fundingSources)
{
XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
string institution = (string)fundingSource;
if (dictLabels.ContainsKey(institution))
{
institutionWrap.Add(new XElement("institution-id", new object[] {
new XAttribute("institution-id-type","fundref"),
dictLabels[institution]
}));
}
else
{
Console.WriteLine("Dictionary doesn't contain : '{0}'", institution);
}
}
Console.ReadLine();
}
}
}
I think this is what you are looking for (MODIFIED jdweng's CODE A LITTLE)
const string FILENAME = #"c:\temp\test.xml";
const string DATABASE = #"c:\temp\test1.xml";
public static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement article = doc.Root;
XNamespace ns = article.GetDefaultNamespace();
XDocument docDatabase = XDocument.Load(DATABASE);
XElement rdf = docDatabase.Root;
XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
XNamespace nsSkos = rdf.GetNamespaceOfPrefix("skos");
XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");
List<XElement> prefLabels = rdf.Descendants(nsSkos + "Concept").ToList();
Dictionary<string, List<string>> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Parent.Element(nsSkos+"Concept").Attribute(nsRdf + "about").Value.Substring(18))
.ToDictionary(x => x.Key, y => y.ToList());
List<XElement> fundingSources = article.Descendants(ns + "funding-source").ToList();
foreach (XElement fundingSource in fundingSources)
{
XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
string institution = (string)fundingSource;
if (dictLabels.ContainsKey(institution))
{
institutionWrap.Add(new XElement("institution-id", new object[] {
new XAttribute("institution-id-type","fundref"),
dictLabels[institution]
}));
}
}
doc.Save(FILENAME);
Console.WriteLine("Done");
Console.ReadLine();
}