pdf*_*age 4 c# xml linq xml-namespaces
问题更新:如果我的问题不清楚,我很抱歉
这是我现在使用的代码
XDocument doc = XDocument.Parse(framedoc.ToString());
foreach (var node in doc.Descendants("document").ToList())
{
XNamespace ns = "xsi";
node.SetAttributeValue(ns + "schema", "");
node.Name = "alto";
}
Run Code Online (Sandbox Code Playgroud)
这是输出
<alto p1:schema="" xmlns:p1="xsi">
Run Code Online (Sandbox Code Playgroud)
我的目标是这样的
xsi:schemaLocation=""
Run Code Online (Sandbox Code Playgroud)
在什么地方p1
以及xmlns:p1="xsi"
来自?
当你写
XNamespace ns = "xsi";
Run Code Online (Sandbox Code Playgroud)
那就是创建一个XNamespace
只有“xsi”的 URI。那不是你想要的。你想要一个命名空间别名的xsi
经...与适当的URIxmlns
属性。所以你要:
XDocument doc = XDocument.Parse(framedoc.ToString());
foreach (var node in doc.Descendants("document").ToList())
{
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
node.SetAttributeValue(XNamespace.Xmnls + "xsi", ns.NamespaceName);
node.SetAttributeValue(ns + "schema", "");
node.Name = "alto";
}
Run Code Online (Sandbox Code Playgroud)
或者更好,只需在根元素设置别名:
XDocument doc = XDocument.Parse(framedoc.ToString());
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
doc.Root.SetAttributeValue(XNamespace.Xmlns + "xsi", ns.NamespaceName);
foreach (var node in doc.Descendants("document").ToList())
{
node.SetAttributeValue(ns + "schema", "");
node.Name = "alto";
}
Run Code Online (Sandbox Code Playgroud)
创建文档的示例:
using System;
using System.Xml.Linq;
public class Test
{
static void Main()
{
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(
new XElement("root",
new XAttribute(XNamespace.Xmlns + "xsi", ns.NamespaceName),
new XElement("element1", new XAttribute(ns + "schema", "s1")),
new XElement("element2", new XAttribute(ns + "schema", "s2"))
)
);
Console.WriteLine(doc);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<element1 xsi:schema="s1" />
<element2 xsi:schema="s2" />
</root>
Run Code Online (Sandbox Code Playgroud)