我有一个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();
}
答案 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解决方案以删除命名空间