Reputation: 6123
I want to load an XElement from XML string that contains prefixes of namespaces. For example:
string template = @"<com:PersonName>
<com:FirstName>def</com:FirstName>
<com:LastName>abc</com:LastName>
</com:PersonName>";
In above XML com refers to a namespace like xmlns:com = "somevalue"
When I used XElement.Parse(xml)
method it throws an error.
I have also tried to load such XML in XmlDocument and it allows me to achieve this using xmlreader and set namespaces to off but I want to do it using XDocuemnt or XElement.
Is it possible to load this string in Xelement without providing namespace ?
Upvotes: 1
Views: 1354
Reputation: 134841
Ultimately you have to provide a namespace for the prefix, otherwise you won't be able to parse it into an XElement
. One way you can work around this is to add to the string a dummy root element with a namespace definition and parse it. Then get the child element from the parsed node.
var template = @"<com:PersonName>
<com:FirstName>def</com:FirstName>
<com:LastName>abc</com:LastName>
</com:PersonName>";
var fixedTemplate = $"<root xmlns:com=\"somevalue\">{template}</root>";
var element = XElement.Parse(fixedTemplate).Elements().Single();
Upvotes: 2