c# XDocument issue - c#

I am quite new to xml-parsing.
Following very basic tutorials I try to parse the following xml returned by a CalDav server:
<?xml version="1.0" encoding="utf-8" ?>
<multistatus xmlns="DAV:">
<response>
<href>/caldav.php/icalendar.ics</href>
<propstat>
<prop>
<getetag>"xxxx-xxxx-xxxx"</getetag>
</prop>
<status>HTTP/1.1 200 OK</status>
</propstat>
</response>
<sync-token>data:,20</sync-token>
</multistatus>
Now I want to find my "response" descendants as follows:
Doc = XDocument.Parse(response);
foreach (var node in xDoc.Root.Descendants("response")) {
// process node
}
No descendant is found. Am I missing something here? My root is indeed a "multistatus" element, it says it has elements, but it doesn't seem as they can be found by name...
Any help would be much appreciated!

Your response element is actually in a namespace, due to this attribute in the root node:
xmlns="DAV:"
That sets the default namespace for that element and its descendants.
So you need to search for elements in that namespace too. Fortunately, LINQ to XML makes that really simple:
XNamespace ns = "DAV:";
foreach (var node in xDoc.Root.Descendants(ns + "response"))
{
...
}

Related

Parsing XML file with xmlns tag defined but not using namespaces

I am struggling with parsing XPathDocument with XPathNavigator where XML document contains xmlns tag, but no namesapce prefix is used.
<?xml version="1.0" encoding="UTF-8"?>
<Order version="1" xmlns="http://example.com">
<Data>
<Id>1</Id>
<b>Aaa</b>
</Data>
</Order>
SelectSingleNode method requires namespace manager with namespace defined.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
nsmgr.AddNamespace("ns","http://example.com");
As a result I have to start using ns prefix in all XPath expressions, although the original XML file does not use prefixes, for e.g.:
nav.SelectSingleNode("/ns:Order/ns:Data/ns:Id", nsmgr)
This adds an unnecessary complexity.
Is there any way to push XPathNavigator to ignore namespace and its prefixes? Ot at least use of prefixes, as namespace definition itself exists only once, so not much effort
The XML has a default namespace. So each and every XML element is bound to it, visible or not.
It is better to use LINQ to XML.
It is a preferred XML API, and available in the .Net Framework since 2007.
c#
void Main()
{
XDocument xdoc = XDocument.Parse(#"<Order version='1' xmlns='http://example.com'>
<Data>
<Id>1</Id>
<b>Aaa</b>
</Data>
</Order>");
XNamespace ns = xdoc.Root.GetDefaultNamespace();
foreach (XElement elem in xdoc.Descendants(ns + "Data"))
{
Console.WriteLine("ID: {0}, b: {1}"
, elem.Element(ns + "Id")?.Value
, elem.Element(ns + "b")?.Value);
}
}

Adding XElement to XDocument with same namespace

I have a XDocument with the following structure where I want to add a bunch of XElements.
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<CstmrCdtTrfInitn>
<GrpHdr>
...
</GrpHdr>
<!-- loaded nodes go here -->
<CstmrCdtTrfInitn>
</Document>
The XElements have the following structure:
<PmtInf xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
...
</PmtInf>
The problem is that the namespace in child nodes is not supported at the recipients side and since it is the same as the XDocument's namespace - it is redundant. How do I avoid/remove that namespace on the child nodes?
The code that I use right now:
var childNodes = new XElement(NameSpace + "GrpHdr", ...);
XElement[] loadedNodes = ...;//Loads from a service using XElement.Load
var content = new XElement(NameSpace + "CstmrCdtTrfInitn", childNodes,loadedNodes));
When calling Save on XElement or XDocument, there is a flags enum SaveOptions that allow you to control to some extent how the document is written to XML.
The easiest way to achieve what you want (without traversing the structure to remove the redundant attributes) is to use one of these flags: OmitDuplicateNamespaces.
Remove the duplicate namespace declarations while serializing.
You can see in this fiddle that adding this flag changes my example output from this:
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<CstmrCdtTrfInitn>
<GrpHdr />
<PmtInf xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">...</PmtInf>
</CstmrCdtTrfInitn>
</Document>
To this:
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<CstmrCdtTrfInitn>
<GrpHdr />
<PmtInf>...</PmtInf>
</CstmrCdtTrfInitn>
</Document>

How do I get multiple namespaces in XML C#?

Following is the XML format:
<?xml version="1.0" encoding="UTF-8"?>
<package version="2.0" unique-identifier="isbn0000000000000" xmlns="http://www.idpf.org/2007/opf">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
<dc:title>Eltern Family</dc:title>
<dc:creator></dc:creator>
<dc:publisher></dc:publisher>
<dc:rights></dc:rights>
<dc:identifier id="isbn0000000000000">0000000000000</dc:identifier>
<dc:language>de</dc:language>
<dc:date opf:event="publication">2019-02-11</dc:date>
</metadata>
</package>
Here I got the default Namespace by XDocument.Root.GetDefaultNamespace();. But as you can see, there are multiple namespaces in the <metadata> XML node. The problem is that, they are variable i.e., each XML may have different values, so I cannot declare a variable with one fixed value.
How do I get the namespaces, so that I can add values to the descendant elements?
Please help.
Regards
Aman
If, as you say, you want to set the content of dc:rights, then you need to get hold of that element.
You can do this by name - the 'qualified name' is made of of the namespace and a local name. The namespace prefix dc is not actually important in and of itself, it's just used as a shorthand to refer to the namespace within the document.
Assuming you have parsed this XML to an XDocument called doc:
XNamespace dc = "http://purl.org/dc/elements/1.1/"
var rights = doc.Descendants(dc + "rights").Single();
rights.Value = "text";

Error using "Xlmns" in XML document

I want to generate below code snippet into xml with c#:
<?xml version="1.0" encoding="utf-8" ?>
<PrincetonStorageRequest
xmlns="http://munichre.com/eai/dss/pct/v1.0"
requestId="RequestOut_MAG_Test_02"
timestampUtc="2015-02-19T09:25:30.7138903Z">
<StorageItems>
and my code is :
XmlWriter writer = XmlWriter.Create(fileName);
writer.WriteStartDocument(true);
writer.WriteStartElement("PrincetonStorageRequest");
writer.WriteAttributeString("xmlns","http://example.com/abc/dss/pct/v1.0");
writer.WriteAttributeString("requestId",name);
writer.WriteAttributeString("timestampUtc","2015-02-19T09:25:30.7138903Z");
writer.WriteStartElement("StorageItems");
But I am getting
"The prefix " cannot be redefined from " to within the same start element tag.
From your XML and the error, I believe it's because you are adding a default namespace after adding an element with no namespace declaration, so you're effectively creating an element and then changing its namespace.
Try the following code - it stops the error when I test it locally just for the XML I think you're trying to get:
XmlWriter writer = XmlWriter.Create(fileName);
writer.WriteStartDocument(true);
writer.WriteStartElement("PrincetonStorageRequest", "http://example.com/abc/dss/pct/v1.0");
writer.WriteAttributeString("xmlns", "http://example.com/abc/dss/pct/v1.0");
writer.WriteAttributeString("requestId", name);
writer.WriteAttributeString("timestampUtc", "2015-02-19T09:25:30.7138903Z");
writer.WriteStartElement("StorageItems");
So when I create the PrincetonStorageRequest element I am specifying a namespace URI.
Edit: Just to check, this is the XML that gets created but I did have to add the code to write the end elements:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<PrincetonStorageRequest xmlns="http://example.com/abc/dss/pct/v1.0" requestId="RequestOut_MAG_Test_02" timestampUtc="2015-02-19T09:25:30.7138903Z">
<StorageItems/>

Deleting xml:base attribute from an XDocument

I'm currently having trouble deleting a troublesome attribute from my Xdocument's root node: xml:base.
My Xdocument currentDoc:
<root xml:base="texthere">
<child/>
</root>
I looked at the documentation about xml:base here: http://www.w3.org/TR/xmlbase/.
I'm having trouble in my C# code to get rid of this because this xml: prefix doesn't have a declaration like other namespace prefixes.
This is what I have which isn't working:
currentDoc.Root.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
The "xml" namespace is defined:
currentDoc.Root.Attributes(XNamespace.Xml + "base").Remove();

Categories

Resources