Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
<id root="44da1b5a-c56a-46a4-bcb0-fde7784c8409" xmlns="urn:hl7-org:v3">

What I have tried:

I am unable to get this root value from tag in c#
Posted
Updated 28-Oct-21 23:05pm
Comments
PIEBALDconsult 29-Oct-21 9:52am    
The same as you would any XML attribute.

You could use a regular expression.
Have a look at this example:
C#
using System;
using System.Text.RegularExpressions;

namespace ConsoleApp7
{
    class Program
    {
        static void Main()
        {
            var text = "<id root=\"44da1b5a-c56a-46a4-bcb0-fde7784c8409\" xmlns=\"urn:hl7-org:v3\">";

            var match = Regex.Match(text, "root=\"(?<ROOT>.*)\" xmlns");

            if (match.Success)
            {
                var root = match.Groups["ROOT"];

                Console.WriteLine(root);
            }
            else
            {
                Console.WriteLine("root not found.");
            }
            
            Console.ReadLine();
        }
    }
}
 
Share this answer
 
Comments
Richard Deeming 29-Oct-21 4:59am    
Parsing XML with a regex is likely to cause a rift in the space-time continuum. :)
TheRealSteveJudge 29-Oct-21 5:07am    
Indeed, I thought the same at first, but <id root="44da1b5a-c56a-46a4-bcb0-fde7784c8409" xmlns="urn:hl7-org:v3"> is not valid XML and cannot be parsed.
You can verify this fact by using https://www.xmlvalidation.com/
Richard Deeming 29-Oct-21 5:09am    
I know, but it's almost certainly part of a larger XML document. Especially since the OP originally posted his question as a "solution" to an old question about reading XML. :)
TheRealSteveJudge 29-Oct-21 5:27am    
As your solution helps maintaining the space-time continuum you get 5*.
Assuming this is part of a larger XML document, since the fragment you've presented is not valid XML on its own, you need to select the element using the namespace-qualified name.

For example, using LINQ-to-XML:
C#
const string input = "<root><id root=\"44da1b5a-c56a-46a4-bcb0-fde7784c8409\" xmlns=\"urn:hl7-org:v3\"/></root>";
XDocument document = XDocument.Parse(input);

XNamespace ns = "urn:hl7-org:v3";
XElement id = document.Descendants(ns + "id").First();
string root = (string)id.Attribute("root");
// root == "44da1b5a-c56a-46a4-bcb0-fde7784c8409"
Overview - LINQ to XML | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900