C# XmlNavigator – Accessing nested XML elements

I’m working on a C# class XmlNavigator that simplifies XML navigation. Here’s the code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>using System;
using System.Dynamic;
using System.Xml;
public class XmlNavigator : DynamicObject
{
private XmlNode xml;
public XmlNavigator(string doc)
{
var document = new XmlDocument();
document.LoadXml(doc);
this.xml = document;
}
private XmlNavigator(XmlNode xml)
{
this.xml = xml;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return false;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
if(binder.Name.Equals("State"))
result = new XmlNavigator(xml.SelectSingleNode("State"));
else if(binder.Name.Equals("Text"))
result = (xml as XmlDocument)?.DocumentElement.OuterXml;
return true;
}
static void Main(string[] args)
{
string xml =
"<?xml version="1.0" encoding="UTF-8"?>" +
"<State>" +
"<City>New York</City>" +
"</State>";
dynamic xmlObj = new XmlNavigator(xml);
Console.WriteLine(xmlObj.Text ?? string.Empty);
Console.WriteLine(xmlObj.State?.Text ?? string.Empty);
Console.WriteLine(xmlObj.State?.City?.Text ?? string.Empty);
}
}
</code>
<code>using System; using System.Dynamic; using System.Xml; public class XmlNavigator : DynamicObject { private XmlNode xml; public XmlNavigator(string doc) { var document = new XmlDocument(); document.LoadXml(doc); this.xml = document; } private XmlNavigator(XmlNode xml) { this.xml = xml; } public override bool TrySetMember(SetMemberBinder binder, object value) { return false; } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; if(binder.Name.Equals("State")) result = new XmlNavigator(xml.SelectSingleNode("State")); else if(binder.Name.Equals("Text")) result = (xml as XmlDocument)?.DocumentElement.OuterXml; return true; } static void Main(string[] args) { string xml = "<?xml version="1.0" encoding="UTF-8"?>" + "<State>" + "<City>New York</City>" + "</State>"; dynamic xmlObj = new XmlNavigator(xml); Console.WriteLine(xmlObj.Text ?? string.Empty); Console.WriteLine(xmlObj.State?.Text ?? string.Empty); Console.WriteLine(xmlObj.State?.City?.Text ?? string.Empty); } } </code>
using System;
using System.Dynamic;
using System.Xml;

public class XmlNavigator : DynamicObject
{
    private XmlNode xml;

    public XmlNavigator(string doc)
    {
        var document = new XmlDocument();
        document.LoadXml(doc);
        
        this.xml = document;
    }
    
    private XmlNavigator(XmlNode xml)
    {
        this.xml = xml;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        return false;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = null;
        if(binder.Name.Equals("State"))
            result = new XmlNavigator(xml.SelectSingleNode("State"));
        else if(binder.Name.Equals("Text"))
            result = (xml as XmlDocument)?.DocumentElement.OuterXml;
        return true;
    }
    
    static void Main(string[] args)
    {
        string xml =
            "<?xml version="1.0" encoding="UTF-8"?>" +
            "<State>" +
            "<City>New York</City>" +
            "</State>";
        dynamic xmlObj = new XmlNavigator(xml);
        
        Console.WriteLine(xmlObj.Text ?? string.Empty);
        Console.WriteLine(xmlObj.State?.Text ?? string.Empty);
        Console.WriteLine(xmlObj.State?.City?.Text ?? string.Empty);
    }
}

Current behavior:
The current code only allows accessing the Text property of the root element and navigating to the State element.

Question:

How can I modify the TryGetMember method to achieve dynamic access to nested elements like State.City.Text?

Additional notes:
Feel free to remove any unnecessary parts of the code snippet.
You can mention that you’ve already tried implementing logic for State but want to generalize for nested elements (recursive function).

Goal:

I want to be able to access nested elements using dynamic properties. For instance, if the XML has a structure like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><State>
<City>New York</City>
</State>
</code>
<code><State> <City>New York</City> </State> </code>
<State>
  <City>New York</City>
</State>

I would like to access the city name using xmlObj.State.City.Text.

1

Here is one possible method. (Warning: this is a “rough-and-ready” solution. For a more robust approach, use an alternative method such as deserialising to a class.)

Add the Newtonsoft.Json NuGet package and the following using declaration:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>using Newtonsoft.Json;
</code>
<code>using Newtonsoft.Json; </code>
using Newtonsoft.Json;

Then you can do this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Convert to JSON:
var doc = XDocument.Parse(xml);
var jsonAsText = JsonConvert.SerializeXNode(doc);
// Parse dynamically:
dynamic xmlObj = JsonConvert.DeserializeObject<ExpandoObject>(jsonAsText);
var state = xmlObj.State;
var city = state.City;
// Access city name directly from deserialised object:
var cityName = (string)xmlObj.State.City;
</code>
<code>// Convert to JSON: var doc = XDocument.Parse(xml); var jsonAsText = JsonConvert.SerializeXNode(doc); // Parse dynamically: dynamic xmlObj = JsonConvert.DeserializeObject<ExpandoObject>(jsonAsText); var state = xmlObj.State; var city = state.City; // Access city name directly from deserialised object: var cityName = (string)xmlObj.State.City; </code>
// Convert to JSON:
var doc = XDocument.Parse(xml);
var jsonAsText = JsonConvert.SerializeXNode(doc);
    
// Parse dynamically:
dynamic xmlObj = JsonConvert.DeserializeObject<ExpandoObject>(jsonAsText);
var state = xmlObj.State;
var city = state.City;

// Access city name directly from deserialised object:
var cityName = (string)xmlObj.State.City;

Again, this is not necessarily recommended for serious software, but for quick tools it can be a useful quick option.

(If you don’t want to “cheat” by converting to JSON, you’ll need a different approach.)

Should work:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public override bool TryGetMember(GetMemberBinder binder, out object? result)
{
if (binder.Name == "Text")
result = xml.InnerText;
else
result = new XmlNavigator(xml.SelectSingleNode(binder.Name));
return true;
}
</code>
<code>public override bool TryGetMember(GetMemberBinder binder, out object? result) { if (binder.Name == "Text") result = xml.InnerText; else result = new XmlNavigator(xml.SelectSingleNode(binder.Name)); return true; } </code>
public override bool TryGetMember(GetMemberBinder binder, out object? result)
{
    if (binder.Name == "Text")
        result = xml.InnerText;
    else
        result = new XmlNavigator(xml.SelectSingleNode(binder.Name));
        
    return true;
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật