将字符串解析到Xelement时如何添加名称空间?

时间:2019-03-19 12:29:21

标签: c# xml linq xml-namespaces xelement

我希望在下面的Xelement中设置名称空间。如何实现?

string Namespace = "http://mynamespace";
string defaultXml = "<ReferResult><Text> Testing Referred</Text></ReferResult>"

Xelement myXml = XElement.Parse(defaultXml);

// How to add the name space to myXml?

1 个答案:

答案 0 :(得分:1)

XNamespace Namespace = "http://mynamespace";
string defaultXml = "<ReferResult><Text> Testing Referred</Text></ReferResult>";

XElement myXml = XElement.Parse(defaultXml);
myXml.Name = Namespace + myXml.Name.LocalName;

//If you want the children to have the same namespace, use the following.
//If you want only the parent to have the namespace, omit the code bellow 
foreach(var element in myXml.Descendants()){
    element.Name = Namespace + element.Name.LocalName;
}

//Output:
//<ReferResult xmlns="http://mynamespace">
//    <Text> Testing Referred</Text>
//</ReferResult>

编辑:根据注释中OP的要求,要删除名称空间,只需使用相同的代码,但忽略名称空间部分:

myXml.Name = myXml.Name.LocalName;
foreach(var element in myXml.Descendants()){
    element.Name = element.Name.LocalName;
}