[英]C# Write XElement with namespace prefix but not including that in Root element
供參考,請參閱: 此問題
在上面的要求是寫
<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
<ci:field1>test</ci:field1>
<ca:field2>another test</ca:field2>
</root>
並為此提供了代碼
但是我的要求是寫
<myrootelement>
<ci:field1>test</ci:field1>
<ca:field2 ca:attrb1="value">another test</ca:field2>
</myrootelement>
因為此元素將成為另一個大XML的一部分,該XML包含自己的ci和ca命名空間引用。 現在,“ <myrootelement>
”作為子級通過api插入api,因此我無權訪問XSD或命名空間等。
我嘗試過的
XElement element = new XElement("myrootelement",
new XElement(ci + "field1", "test"),
new XElement(ca + "field2", "another test", new XAttribute(ca + "attrb1", "value")));
但這會產生:
<myrootelement>
<field1 xmlns="http://somewhere.com">test</field1>
<field2 p2:attrb1="value" xmlns:p2="http://somewhereelse.com" xmlns="http://somewhereelse.com">another test</field2>
</myrootelement>
編輯:添加更多詳細信息
然后使用以下元素將上述元素發送到Rest API
{
.
.
var client = new RestClient(uri);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddParameter("text/xml", elem, ParameterType.RequestBody);
.
.
}
您嘗試生成的不是XML,因為它不符合XML規范,因此不要指望LINQ-to-XML這樣的XML API可以為您做到這一點。 最好的選擇是生成一個適當的XML,其中包括名稱空間定義(如果此時沒有該信息,則可以使用偽造的URI),然后執行一些字符串操作操作(正則表達式或簡單的String.Replace()
)之后刪除這些名稱空間。
也許這個問題只是一個XY問題 ,因為假設您仍在使用某種XML API,則插入不符合XML規范的字符串(在下一步中要執行)也可能會引起問題。任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.