Can you get the prefix, not the namespace, from an XElement?

A

AK

Hiya,

I've got some xml elements that look like this:
<dc:title xml:lang="fr">myTitle</dc:title>

I would like to be able to get the name with the prefix, i.e.
'dc:title', but I can only manage to get either 'title' only or the
namespace (xmlns:dc="http://purl.org/dc/elements/1.1/"). Code is
below.

XElement xml = XElement.Load(metadataPath);

foreach (XElement child in xml.Elements())
{
string childElement = child.Name.LocalName; // returns 'title'
string namespace= child.Name.NamespaceName; // returns 'http://
purl.org/dc/elements/1.1/'
}

Is it possible to get out what I want from this?

Many thanks,

AK
 
M

Martin Honnen

AK said:
I've got some xml elements that look like this:
<dc:title xml:lang="fr">myTitle</dc:title>

I would like to be able to get the name with the prefix, i.e.
'dc:title', but I can only manage to get either 'title' only or the
namespace (xmlns:dc="http://purl.org/dc/elements/1.1/").

Here is how you can find the prefix:

XElement el = XElement.Parse(@"<dc:title
xmlns:dc=""http://purl.org/dc/elements/1.1/""
xml:lang=""fr"">myTitle</dc:title>");
Console.WriteLine(el.GetPrefixOfNamespace(el.Name.Namespace));


You already know how to find the local name.
 
A

AK

Here is how you can find the prefix:
             XElement el = XElement.Parse(@"<dc:title
xmlns:dc=""http://purl.org/dc/elements/1.1/""
xml:lang=""fr"">myTitle</dc:title>");
             Console.WriteLine(el.GetPrefixOfNamespace(el.Name.Namespace));

Brilliant, works perfectly! Thank you for answering.

Cheers,

AK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top