0

I need to write the code in C#.

I get the following string containing xml elements.

**"\n                        <iqn:CDFID xmlns:iqn=\"ns:iqn:cwm:1.0\">Clearance Type</iqn:CDFID>\n                        <iqn:CDFName xmlns:iqn=\"ns:iqn:cwm:1.0\">Clearance Type</iqn:CDFName>\n                        <iqn:CDFValue xmlns:iqn=\"ns:iqn:cwm:1.0\">THE ACTUAL VALUE</iqn:CDFValue>\n                     "**

The elements are CDFID CDFName CDFValue

The above 3 elements could be in any order inside the string. How do I identify the CDFValue xml element and extract the value "THE ACTUAL VALUE" out.

How can I treat the string in an xml manner and get the value of the desired element out.

dotnet-practitioner
  • 13,968
  • 36
  • 127
  • 200

1 Answers1

3

There're several things to consider:

  1. The string contains multiple elements, which is not a valid XML document, you need to either parse it as document fragment, or add a root element by yourself.

  2. The element has namespace in it, you need to create namespace to access the node.

I prefer to use XDocument over XmlDocument. Here's the sample code to get the actual value:

var validXml = "<root>" + value + "</root>";
var doc = XDocument.Parse(validXml);

var ns = XNamespace.Get("ns:iqn:cwm:1.0");
Console.WriteLine(doc.Root.Element(ns.GetName("CDFValue")).Value);

Prints out "THE ACTUAL VALUE"

jiulongw
  • 355
  • 3
  • 5