I have an xml whose root has namespaces like
<root version="2.0" xsi:schemaLocation="http://www.sample.org/schemas/2009 http://www.sample1.org/schemas/2009/railML-2.0/railML.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dc="http://xyz/elements/1.1/" xmlns="http://www.abcd.org/schemas/2009">
I am able to retrieve the value of xmlns using
var xdoc = XDocument.Load(XmlToParse);
Console.WriteLine(xdoc.Root.Name.NamespaceName);
but how can i get the values of other namespaces in root i.e. value of
xsi
dc
schemaLocation
Before parsing I need to verify these namespaces so i need these values.
how to do it?
can it be done by linq how?
var q = xdoc.Root.Attributes()
.Where(x => x.IsNamespaceDeclaration)
.Select(x => new {Prefixes = x.Name.LocalName, ns = x.Value});
EDIT:
More Ways: Get namespaces from an XML Document with XPathDocument and LINQ to XML
Related
I am trying to read the values of the elements present in XML. It is working properly if input doesn't contains any namespaces related attributes in that XML as below -
string testInputXML = #"
<FIXML>
<Header>
<RequestHeader>
<MessageKey>
<RequestUUID>Req_1499940064961</RequestUUID>
<ServiceRequestId>getLastNTransactionsWithPagination</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>COR</ChannelId>
<LanguageId></LanguageId>
</MessageKey>
</RequestHeader>
</Header>
<isLogging>true</isLogging>
</FIXML>
";
XElement myElement = XElement.Parse(testInputXML);
Console.WriteLine(myElement.Element("isLogging").Value);
If input XML contains any namespaces related attributes then it is throwing exception.
Object reference not set to an instance of an object.
string testInputXML = #"
<FIXML xsi:schemaLocation=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://www.w3.org/fixml"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<Header>
<RequestHeader>
<MessageKey>
<RequestUUID>Req_1499940064961</RequestUUID>
<ServiceRequestId>getLastNTransactionsWithPagination</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>COR</ChannelId>
<LanguageId></LanguageId>
</MessageKey>
</RequestHeader>
</Header>
<isLogging>true</isLogging>
</FIXML>
";
XElement myElement = XElement.Parse(testInputXML);
Console.WriteLine(myElement.Element("isLogging").Value);
Is there any way to exclude the namespaces present in the XML while fetching element values?
Try this:
Console.WriteLine(myElement.DescendantsAndSelf().Elements().FirstOrDefault(d => d.Name.LocalName == "isLogging")?.Value);
Try using XPath like this:
XDocument xmlDoc = XDocument.Parse(xml);
XElement element = xmlDoc.XPathSelectElement("/*[name()='FIXML']/*[name()='isLogging']");
My goal is to be able to retrieve the value of <Cdtr><Id> from this XML file:
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:com.firmaname:response.002">
<DocId>1261076951</DocId>
<CreateDtTm>2016-11-23T14:53:23.938Z</CreateDtTm>
<ResponseCd>OK</ResponseCd>
<Dbtr>
<Id>debtorId</Id>
<Name>debtorName</Name>
</Dbtr>
<Cdtr>
<Id>creditorId</Id>
<Name>creditorName</Name>
</Cdtr>
</Document>
Note that this file 2 <Id> nodes, so I must specify the exact path to the node. The result should be 'creditorId'.
My code is:
XNamespace ns = "urn:com.firmaname:response.002";
var results = requestMessage.Descendants(ns + "Id").First().Value;
But this will return 'debtorId'. I've searched here to find a way to retrieve an exact path, but they all seem to involve using Xpath with XElement. When using XElement I run into trouble with the namespace. All of the suggestions I find are about using XDocument...
I would still use XDocument and select the Cdtr node, then the Id node within it.
One hack you can do with namespaces if you are confident you don't need them is to use <element>.Name.LocalName.
XDocument doc = XDocument.Load("<path to xml");
XNamespace ns = "urn:com.firmaname:response.002";
var creditorid = doc.Descendants().Elements()
.Where(e => e.Name == ns + "Cdtr").Elements()
.First(e => e.Name == ns + "Id");
Update using LocalName
var creditorid = doc.Descendants().Elements()
.Where(e => e.Name.LocalName == "Cdtr").Elements()
.First(e => e.Name.LocalName == "Id");
This works, however you should use the namespace if you can.
I have to read some tags and attributes from an XML that has a defined structure but since those files can be generated from different sources, they can have different namespaces and prefixes.
This is the first XML sample
<Order xmlns="urn:oasis:names:specification:ubl:schema:xsd:Order-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<cbc:UBLVersionID>2.1</cbc:UBLVersionID>
<cbc:CustomizationID>urn:www.cenbii.eu:transaction:biitrns001:ver2.0:extended:urn:www.peppol.eu:bis:peppol3a:ver2.0:extended:urn:www.ubl-italia.org:spec:ordine:ver2.1</cbc:CustomizationID>
<cbc:ID>ORD-001</cbc:ID>
<cbc:IssueDate>2016-10-01</cbc:IssueDate>
<cbc:OrderTypeCode listID="UNCL1001">221</cbc:OrderTypeCode>
<cac:ValidityPeriod>
<cbc:EndDate>2024-10-19</cbc:EndDate>
</cac:ValidityPeriod>
<cac:BuyerCustomerParty>
<cac:Party>
<cbc:EndpointID schemeID="IT:IPA">ITAK12MH</cbc:EndpointID>
<cac:PartyIdentification>
<cbc:ID schemeID="IT:VAT">01567570254</cbc:ID>
</cac:PartyIdentification>
<cac:PartyName>
<cbc:Name>A Custom Name</cbc:Name>
</cac:PartyName>
</cac:Party>
</cac:BuyerCustomerParty>
</Order>
This is the second XML sample with different namespaces and prefixes, but same structure (tags, attributes).
<ns10:Order xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ns2="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:ns3="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:ns4="http://www.w3.org/2000/09/xmldsig#" xmlns:ns5="http://uri.etsi.org/01903/v1.3.2#" xmlns:ns6="urn:oasis:names:specification:ubl:schema:xsd:SignatureBasicComponents-2" xmlns:ns7="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:ns8="http://uri.etsi.org/01903/v1.4.1#" xmlns:ns9="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2" xmlns:ns10="urn:oasis:names:specification:ubl:schema:xsd:Order-2">
<UBLVersionID>2.1</UBLVersionID>
<CustomizationID>urn:www.cenbii.eu:transaction:biitrns001:ver2.0:extended:urn:www.peppol.eu:bis:peppol3a:ver2.0:extended:urn:www.ubl-italia.org:spec:ordine:ver2.1</CustomizationID>
<ID>ORD-001</ID>
<IssueDate>2016-10-01</IssueDate>
<OrderTypeCode listID="UNCL1001">221</OrderTypeCode>
<ns3:ValidityPeriod>
<EndDate>2024-10-19</EndDate>
</ns3:ValidityPeriod>
<ns3:BuyerCustomerParty>
<ns3:Party>
<EndpointID schemeID="IT:IPA">ITAK12MH</EndpointID>
<ns3:PartyIdentification>
<ID schemeID="IT:VAT">01567570254</ID>
</ns3:PartyIdentification>
<ns3:PartyName>
<Name>A Custom Name</Name>
</ns3:PartyName>
</ns3:Party>
</ns3:BuyerCustomerParty>
</ns10:Order>
Those files must be considered the same and so both valid.
A third example can be a file similar to the second where the namespaces are the same but their prefixes are different. Obviously the important thing is that the prefix used to match the namespace belongs to that particular tag.
I have no way of knowing in advance what will be the prefixes associated with namespaces.
<aaa:Order xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:aaa="urn:oasis:names:specification:ubl:schema:xsd:Order-2" xmlns:bbb="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2">
<UBLVersionID>2.1</UBLVersionID>
<CustomizationID>urn:www.cenbii.eu:transaction:biitrns001:ver2.0:extended:urn:www.peppol.eu:bis:peppol3a:ver2.0:extended:urn:www.ubl-italia.org:spec:ordine:ver2.1</CustomizationID>
<ID>ORD-001</ID>
<IssueDate>2016-10-01</IssueDate>
<OrderTypeCode listID="UNCL1001">221</OrderTypeCode>
<bbb:ValidityPeriod>
<EndDate>2024-10-19</EndDate>
</bbb:ValidityPeriod>
<bbb:BuyerCustomerParty>
<bbb:Party>
<EndpointID schemeID="IT:IPA">ITAK12MH</EndpointID>
<bbb:PartyIdentification>
<ID schemeID="IT:VAT">01567570254</ID>
</bbb:PartyIdentification>
<bbb:PartyName>
<Name>A Custom Name</Name>
</bbb:PartyName>
</bbb:Party>
</bbb:BuyerCustomerParty>
</aaa:Order>
This last file must be considered valid as the others.
As you can see, the association between the tags and their namespaces are always the same. The only things that are changed are the prefixes.
My actual code uses XDocument and XElement classes to read the XML but it can be the way because I need to know the exact prefix for each tag and since they can vary, it works only with the first XML file sample.
XDocument doc;
XmlNamespaceManager manager;
using (XmlReader reader = XmlReader.Create(stream))
{
doc = XDocument.Load(reader);
// Retrieving namespaces of XML file
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToFollowing(XPathNodeType.Element);
IDictionary<string, string> namespaces = navigator.GetNamespacesInScope(XmlNamespaceScope.All);
// Add namespaces to an XmlNamespaceManager to read nodes
manager = new XmlNamespaceManager(reader.NameTable);
foreach (KeyValuePair<string, string> ns in namespaces)
{
manager.AddNamespace(ns.Key, ns.Value);
}
}
XElement currentNode;
currentNode = doc.Root.XPathSelectElement("cbc:ID", manager);
if (currentNode != null)
item.DespatchAdviceId = currentNode.Value;
currentNode = doc.Root.XPathSelectElement("cbc:IssueDate", manager);
if (currentNode != null)
{
DateTime dataEmissione;
if (DateTime.TryParseExact(currentNode.Value, validDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dataEmissione))
item.OrderIssueDate = dataEmissione;
}
currentNode = doc.Root.XPathSelectElement("cac:BuyerCustomerParty/cac:Party/cac:PartyIdentification/cbc:ID", manager);
if (currentNode != null)
{
item.BuyerPartyId = currentNode.Value;
if (currentNode.Attribute("schemeID") != null)
item.BuyerPartySchemeId = currentNode.Attribute("schemeID").Value;
}
// ... and so on...
How can I read the XMLs without having to specify the namespace prefixes?
Should I use another .NET library or maybe a 3rd party one?
Using LocalName, you can linq it without adding the namespace.
//this is for <cbc:ID>ORD-001</cbc:ID>
var element = doc.Root.Elements().Where(x => x.Name.LocalName == "ID").FirstOrDefault();
If you want to go in the nested elements
var element = doc.Root.Elements().Where(x => x.Name.LocalName == "ValidityPeriod").
Elements().Where(x=> x.Name.LocalName == "EndDate").FirstOrDefault();
I need to know the exact prefix for each tag.
No, you don't. The prefixes are entirely irrelevant to qualified name of an element or attribute. If you want to go the XPath route, then don't read the namespaces and prefixes from the document to create your namespace manager, specify them yourself so you know what they are. Then use those in your query. For example, this will work with any of your XML documents:
var manager = new XmlNamespaceManager(new NameTable());
manager.AddNamespace("cbc",
"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
var id = doc.Root.XPathSelectElement("cbc:ID", manager);
What I would encourage, though, is that you ditch XPath. LINQ to XML is so much nicer. And another quick hint, there is an overload of XDocument.Load that accepts a stream. There's no need to create the XmlReader. So:
XNamespace order = "urn:oasis:names:specification:ubl:schema:xsd:Order-2";
XNamespace cbc = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
XNamespace cac = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
var doc = XDocument.Load(stream);
var id = (string) doc.Elements(order + "Order")
.Elements(cbc + "ID")
.Single();
var issueDate = (DateTime) doc.Elements(order + "Order")
.Elements(cbc + "IssueDate")
.Single();
var buyerPartySchemeId = (string) doc.Descendants(cac + "BuyerCustomerParty")
.Descendants(cbc + "ID")
.Attributes("schemeID")
.Single();
I am trying to find nodes in an XML document like this:
<?xml version="1.0"?>
<TrainingCenterDatabase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
<Activities>
<Activity Sport="CyclingTransport">
<Id>2014-07-08T15:28:14Z</Id>
</Activity>
</Activities>
</TrainingCenterDatabase>
I aim to extract the node value 'Id' with code like this:
XDocument doc = XDocument.Load(filePath);
List<string> urlList = doc.Root.Descendants("Id")
.Select(x => (string)x)
.ToList();
Console.WriteLine(urlList.Count);
However the count is 0, where I expect 1.
After some debugging and editing the XML I noticed that if I change the TrainingCenterDatabase node and remove the attributes to this:
<TrainingCenterDatabase>
Then the result is a count of 1 as expected.
So my question is how do I take into account the namespaces so that I can get the value when the TrainingCenterDatabase node has these attributes?
Namespaces in XML can be tricky. I've run into this problem myself a number of times. In all likelihood, the following will fix your problem:
XDocument doc = XDocument.Load(filePath);
List<string> urlList = doc.Root.Descendants(doc.Root.Name.Namespace.GetName("Id"))
.Select(x => (string)x)
.ToList();
Console.WriteLine(urlList.Count);
Basically, this just assumes the underlying element to have the same namespace as your root element. That's true in this case, but of course it doesn't have to be.
The right way, probably, is to do it explicitly. Now, granted, that kind of depends on how you're using this and your datasource, so make the decision for yourself, but that would require doing something more like this:
XDocument doc = XDocument.Load(filePath);
List<string> urlList = doc.Root.Descendants(System.Xml.Linq.XName.Get("Id", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"))
.Select(x => (string)x)
.ToList();
Console.WriteLine(urlList.Count);
The cause for your problem was that the default behavior for XElement, when not given an explicit namespace, is to assume no namespace. However, the default behavior for the XML spec is to assume the parent's namespace. In your case, those two were different, so it wasn't able to find the descendant.
It Works...
XDocument doc = XDocument.Load(filePath);
XNamespace ns = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2";
var root = doc.Descendants(ns + "Id").Select(x => x.Value).ToList();
Console.WriteLine(root.Count);
Let's say I have this XML file:
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>
And now I want to print all the names of the node:
Names
Name
FirstName
LastName
I managed to get the all in a XmlNodeList, but I dont know how SelectNodes works.
XmlNodeList xnList = xml.SelectNodes(/*What goes here*/);
I want to select all nodes, and then do a foreach of xnList (Using the .Value property I assume).
Is this the correct approach? How can I use the selectNodes to select all the nodes?
Ensuring you have LINQ and LINQ to XML in scope:
using System.Linq;
using System.Xml.Linq;
If you load them into an XDocument:
var doc = XDocument.Parse(xml); // if from string
var doc = XDocument.Load(xmlFile); // if from file
You can do something like:
doc.Descendants().Select(n => n.Name).Distinct()
This will give you a collection of all distinct XNames of elements in the document. If you don't care about XML namespaces, you can change that to:
doc.Descendants().Select(n => n.Name.LocalName).Distinct()
which will give you a collection of all distinct element names as strings.
There are several ways of doing it.
With XDocument and LINQ-XML
foreach(var name in doc.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct())
{
Console.WriteLine(name);
}
If you are using C# 3.0 or above, you can do this
var data = XElement.Load("c:/test.xml"); // change this to reflect location of your xml file
var allElementNames =
(from e in in data.Descendants()
select e.Name).Distinct();
Add
using System.Xml.Linq;
Then you can do
var element = XElement.Parse({Your xml string});
Console.Write(element.Descendants("Name").Select(el => string.Format("{0} {1}", el.Element("FirstName").Value, el.Element("LastName").Value)));