如何将char :
添加到XML元素属性?
输出应该如何显示
<alto xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.loc.gov/standards/alto/ns-v3#"
xsi:schemaLocation="http://www.loc.gov/standards/alto/ns-v3# http://www.loc.gov/standards/alto/v3/alto-3-1.xsd" SCHEMAVERSION="3.1"
xmlns:xlink="http://www.w3.org/1999/xlink">
到目前为止这是我的代码
var z = doc.Descendants("alto").First();
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
z.Add(new XAttribute(XNamespace.Xmlns + "xsi", ns.NamespaceName));
我尝试了这段代码,但它给了我错误
new XAttribute("xmlns", "http://www.loc.gov/standards/alto/ns-v3#")
以下是错误消息:
前缀''无法在相同的起始元素标记内从''重新定义为'http://www.loc.gov/standards/alto/ns-v3#'
答案 0 :(得分:0)
您应该将默认命名空间放在最后。对于像你这样的复杂命名空间,我通常只需解析字符串,如下面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<alto xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://www.loc.gov/standards/alto/ns-v3#\"" +
" xsi:schemaLocation=\"http://www.loc.gov/standards/alto/ns-v3# http://www.loc.gov/standards/alto/v3/alto-3-1.xsd\" SCHEMAVERSION=\"3.1\"" +
" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" +
"</alto>";
XDocument doc = XDocument.Parse(xml);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
XNamespace nsXsi = root.GetNamespaceOfPrefix("xsi");
XNamespace nsSchemaLocation = root.GetNamespaceOfPrefix("schemaLocation");
XNamespace nsXlink = root.GetNamespaceOfPrefix("xlink");
}
}
}