将字符串解析为 Xelement 时如何添加命名空间?
How to add a namespace when parsing string to 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?
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;
}
我希望将命名空间设置为下面的 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?
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;
}