如何更改具有命名空间的属性的值?

How do I change the value of an attribute that has a namespace?

以下是 XML 格式:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en">
<head>
<meta name="dtb:uid" content="0000000000000"/>
<meta name="dtb:depth" content="1"/>
<meta name="dtb:totalPageCount" content="pageNumber"/>
<meta name="dtb:maxPageNumber" content="0"/>
</head>
</ncx>

我需要更改 xml:lang 的值,但我不知道该怎么做。

我的 C# 代码:

xtabdoc.Root.Descendants().FirstOrDefault(el =>(string)el.Attribute(XNamespace.Xml + "lang") == "en");

显示为空

请帮忙。

您可以通过以下方式获取元素。

var result = XDocument.Parse(xmlString).Descendants().FirstOrDefault(el =>(string)el.Attribute(XNamespace.Xml + "lang") == "en");

关键在于Element在Root中。所以当你使用 Root.Descendants 时,你没有考虑节点,这就是为什么你得到 null.

简单:

           XDocument doc = XDocument.Load(FILENAME);
            XElement root = doc.Root;
            XAttribute lang = root.Attributes().Where(x => x.Name.LocalName == "lang").FirstOrDefault();
            lang.SetValue("abc");