C# 使用XDocument更改XML文件的问题

C# 使用XDocument更改XML文件的问题,c#,xml,linq,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"> 如果代码中有输入错误,则查找xlmns而不是xmlns属性。也就

我有一个XML文件,我想修改它,但由于某些原因,它不允许我修改特定的元素。我这样调用文件:

XDocument doc = XDocument.Load(@"C:\t.xml");
但当我尝试使用LINQ或任何其他形式时,它返回null。我检查了,文档有模式标记和名称空间:

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

如果代码中有输入错误,则查找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属性不会从所有节点中删除名称空间。可能会看到删除名称空间的解决方案

我会想象您有一个给定名称空间的任意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>
这将产生

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

请发布一个返回nullupdated Question的代码示例。您需要将名称空间附加到元素查询中,或者使用它的localname-hint,google termsTry:XNamespace ns=schema.GetDefaultNamespace;XNamespace nsXs=schema.GetNamespaceOfPrefixxs;您可以使用Elementns+NAME或ElementnsXs+NAME查找元素我为整个图片添加了要点
<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; }
}