使用XDocument更改XML文件的问题

时间:2018-01-09 11:34:03

标签: c# xml linq

我有一个XML文件,我想改变,但由于某种原因,它不会让我改变特定的元素。我正在调用这样的文件:

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

但是当我尝试使用LINQ或任何其他形式时,它返回null。我检查过,文档中有架构标签和命名空间:

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

一旦这些被删除我可以改变元素但是当它们进入时,我不能。为此做了什么工作?

代码示例更新

 XElement schema = doc.Element("Document");
        if (schema.Attribute("xlmns") != null && schema.Attribute("xlmns:xs") != null)
        {
            schema.Attribute("xlmns").Remove();
        }

2 个答案:

答案 0 :(得分:1)

我想你有一个带有给定命名空间的任何xml

<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>

并且您希望在现有结构中的某处添加新元素。 为了更改xml,您不需要删除命名空间,但是您需要与命名空间一起使用。 请注意,命名空间用于查询和追加。

// 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);
}

将产生

<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>

为了完整性,请参阅下面我使用

的映射类
[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; }
}

答案 1 :(得分:0)

您的代码中有拼写错误,您需要查找xlmns而不是xmlns属性。话虽这么说,要获取xs属性,您需要在其前面添加xml命名空间。

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(); 
}

注意:删除xmlns属性不会从所有节点中删除命名空间。也许请参阅this解决方案以删除命名空间