getting part of xml from xml document via c#

LALITHA KRISHNA 41 Reputation points
2022-04-13T17:19:45.027+00:00

i have an xml the structure is complex

<da:main xmlns:da="namespace1">
<da:siteinfo>*</da:siteinfo>
<da:Header></da:Header>
<da:Body>
<ap:header xmlns:ap="namespace2"></ap:header>
<d:Details xmlns:d="namespace3"></d:Details>

</da:Body>
</da:main>

how can i get Details session as a separate xml with namespace and prefix?

Microsoft BizTalk Server
Microsoft BizTalk Server
A family of Microsoft server products that support large-scale implementation management of enterprise application integration processes.
347 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,154 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 55,366 Reputation points
    2022-04-13T20:24:42.63+00:00

    in xml docs, the namespace name is fixed, but the prefix can vary by document. something like:

    XmlNode? GetDetails(XmlDocument doc)
    {
        var nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("n1", "namespace1");
        nsmgr.AddNamespace("n2", "namespace2");
        nsmgr.AddNamespace("n3", "namespace3");
    
        var xPathString = "//n1:main/n1:Body/n3:Details";
        var xmlNode = doc.DocumentElement!.SelectSingleNode(xPathString, nsmgr);
        return xmlNode;
    }
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Colin Dijkgraaf 1,346 Reputation points
    2022-04-14T03:51:35.31+00:00

    In BizTalk would create a schema that has that desired structure and namespace, and then map from the original schema to the new schema.

    Namespace prefixes don't have to be unique except within the same payload, and you can't control that easily in BizTalk, and you shouldn't have to.

    0 comments No comments

  2. Yitzhak Khabinsky 24,941 Reputation points
    2022-04-14T16:13:26.877+00:00

    Hi @LALITHAKAKARAPALLI-1754,

    Here is a most efficient method by using LINQ to XML API.
    It is available in the .Net Framework since 2007.

    c#

    void Main()
    {
        XDocument xdoc = XDocument.Parse(@"<da:main xmlns:da='namespace1'>
            <da:siteinfo>*</da:siteinfo>
            <da:Header></da:Header>
            <da:Body>
                <ap:header xmlns:ap='namespace2'></ap:header>
                <d:Details xmlns:d='namespace3'>
                    <d:child1></d:child1>
                    <d:child2></d:child2>
                </d:Details>
            </da:Body>
        </da:main>");
    
        XNamespace ns = "namespace3";
        var xmlNode = xdoc.Descendants(ns + "Details");
    
        Console.Write(xmlNode);
    }
    

    Output

    <d:Details xmlns:d="namespace3">
      <d:child1></d:child1>
      <d:child2></d:child2>
    </d:Details>
    
    0 comments No comments