[英]Add xsi:type to my XML document
我有使用此Web服務方法提取XML文檔類型的代碼
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XAttribute attribute = new XAttribute(xsi + "type", "xsd:string");
XElement node_user_id = new XElement("user_id", attribute, user.code);
XDocument doc = new XDocument(new XElement("ranzcp_user", new XAttribute(XNamespace.Xmlns + "ns1", "urn:logon"), node_user_id));
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(elem.ToString());
使用上面的代碼,我能夠完全像這樣提取一個xml文檔:
<ranzcp_user xmlns:ns1="urn:logon">
<user_id xmlns:p3="http://www.w3.org/2001/XMLSchema-instance" p3:type="xsd:string">12345678</user_id>
</ranzcp_user>
但是我真正需要的是:
<ranzcp_user xmlns:ns1="urn:logon">
<user_id xsi:type="xsd:string">12345678</user_id>
</ranzcp_user>
有什么方法可以獲取xml所需的格式,其次,解析xml數據時是否需要xsi:type =“ xsd:string”屬性?
TIA!
您可以顯式定義名稱空間前綴,以便使用規范的xsi
而不是p3
:
var doc = new XDocument(
new XElement("ranzcp_user",
new XAttribute(XNamespace.Xmlns + "ns1", "urn:logon"),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XElement("user_id", 12345678,
new XAttribute(xsi + "type", "xsd:string")
)
)
);
看到這個小提琴 。 這給您:
<ranzcp_user xmlns:ns1="urn:logon" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<user_id xsi:type="xsd:string">12345678</user_id>
</ranzcp_user>
但是,正如已經說過的那樣,完全刪除名稱空間前綴將導致XML無效-沒有合規的處理器可以讓您創建或讀取它而不會出錯。
可能是“必需”的XML在父元素之一中聲明了此前綴嗎? 如果沒有,我建議這是一個錯誤,您應該在花時間嘗試刪除該屬性之前對此進行調查。 我懷疑當使用者發現XML無效時,您最終將花費所有精力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.