0

I have an XML file which i want to alter but for some reason it wont let me alter specific elements. Im calling the file like this:

XDocument doc = XDocument.Load(@"C:\t.xml");

but when i try to use LINQ or any other form it returns null. I checked and the document has schema tags and namespaces:

<Document xmlns="urn:test" xmlns:xs="http://www.w3.org/2001/XMLSchema">

once theses are removed i can alter the elements but when they are in, i cant. What is the work around for this?

Code Sample Update

 XElement schema = doc.Element("Document");
        if (schema.Attribute("xlmns") != null && schema.Attribute("xlmns:xs") != null)
        {
            schema.Attribute("xlmns").Remove();
        }
Nonagon
  • 397
  • 1
  • 5
  • 21

2 Answers2

1

I'll imagine you have a whatever xml with given namespace

<category name=".NET" xmlns="urn:test" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <books>
    <book>CLR via C#</book>
    <book>Essential .NET</book>
  </books>
</category>

And you want to append a new element somewhere in the existing structure. In order to alter the xml, you don't need to remove the namespace, but you need to play along with the namespace. Notice the namespace is used for both queries and appends.

// Parse or Load the document
var document = XDocument.Parse(xml);
var xmlns = document.Root.GetDefaultNamespace();

// Find a specific node
var node = document
    .Descendants(xmlns + "books")
    .FirstOrDefault();
if (node != null)
{
    // Append an element
    var content = new XElement(xmlns + "book", "Linq in action");
    node.Add(content);
}

that will produce

<category name=".NET" xmlns="urn:test" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <books>
    <book>CLR via C#</book>
    <book>Essential .NET</book>
    <book>Linq in action</book>
  </books>
</category>

For completeness, see bellow for the mapping classes i made use of

[XmlRoot(ElementName = "category")]
public class Category
{
    [XmlElement(ElementName = "books")]
    public Books Books { get; set; }

    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "books")]
public class Books
{
    [XmlElement(ElementName = "book")]
    public List<string> Book { get; set; }
}
Dan Dohotaru
  • 2,809
  • 19
  • 15
0

You have a typo in your code, you look for the xlmns not the xmlns attribute. That being said, to get the xs attribute you need to prefix it with the xml namespace.

XDocument doc = XDocument.Parse(@"<Document xmlns=""urn:test"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" />");
XElement schema = doc.Root;
if (schema.Attributes("xmlns") != null && schema.Attribute(XNamespace.Xmlns + "xs") != null)
{

    schema.Attribute("xmlns").Remove(); 
}

Note: Removing the xmlns attribute will not remove the namespace from all nodes. Maybe see this solution for removing the namespace

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357