Chetan Hirapara
Chetan Hirapara

Reputation: 694

How to open xml using XElement?

I'm trying to load metadata.xml file from my machine, but it's gives error like

The ':' character, hexadecimal value 0x3A, cannot be included in a name.

please let me help to find correct way for load xml using XElement.

C# code

private static void xmlProcess()
        {

            string filePath = @"D:\metadata.xml";
            if (System.IO.File.Exists(filePath))
            {

                // load xml file from destination folder
                XElement document = new XElement(filePath);

                var country = "IN";
                var curProduct = document.Elements("country").Where(t => t.Value == country).FirstOrDefault().Parent;

            }
        }

XML File(metadata.xml)

<root version="mech5.2">
  <language>en-US</language>
  <provider>Provider1</provider>
  <data>
    <title>Engine1</title>
    <vendor_id>ABC</vendor_id>
    <products>
      <product>
        <country>IN</country>
        <times>
          <time>
            <start_date>2017-01-15</start_date>
            <end_date>2017-09-15</end_date>
          </time>
        </times>
      </product>
    </products>
  </data>
</root>

why I'm getting this error: "The ':' character, hexadecimal value 0x3A, cannot be included in a name"

Upvotes: 0

Views: 1311

Answers (2)

har07
har07

Reputation: 89285

You can use just XElement.Load() to create and populate XElement from XML file :

XElement document = XElement.Load(filePath);

Upvotes: 2

Sava Glodic
Sava Glodic

Reputation: 113

The issue is that you're trying using a wrong form of the constructor. XElement is trying to turn your filepath string into an instance name, and that's obviously not working. Try this.

XElement x = new XElement();
x.Load(filePath);

ps. double check the declaration of the constructor you're using https://msdn.microsoft.com/en-us/library/bb292758(v=vs.110).aspx

Upvotes: 1

Related Questions