Manipulate XML XDocument XmlDocument C#

本文关键字:XmlDocument XDocument XML Manipulate | 更新日期: 2023-09-27 18:05:01

我需要能够使用这样的模式操作XML:

<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<SOAP-ENVELOPE:Envelope xmlns:SOAP-ENVELOPE='http://schemas.xmlsoap.org/soap/envelope/'>
<SOAP-ENVELOPE:Header>
    <Authorization>
        <FromURI/>
        <User/>
        <Password/>
        <TimeStamp/>
    </Authorization>
    <Notification>
        <NotificationURL/>
        <NotificationExpiration/>
        <NotificationID/>
        <MustNotify/>
    </Notification>
</SOAP-ENVELOPE:Header>
<SOAP-ENVELOPE:Body SOAP-ENVELOPE:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
</SOAP-ENVELOPE:Body>

我需要添加fromi, User, Password, notificationurl, MustNotify等数据,并且在正文中我仍然需要动态添加:

<SOAPSDK4:APIOperation xmlns:SOAPSDK4="http://www.someserver.com/message/">
</SOAPSDK4:APIOperation>

最后在APIOperation中构造web服务所需的结构,但可以使用XDocument轻松地创建树。

一个星期以来,我一直在寻找如何在信封内操作数据的信息,这里我需要用三种不同的级别来做。

Manipulate XML XDocument XmlDocument C#

给你一个想法:

var doc = XDocument.Load(...);
XNamespace envNs = "http://schemas.xmlsoap.org/soap/envelope/";
var fromUri = doc.Root
       .Element(envNs + "Header")
       .Element("Authorization")
       .Element("FromURI");
fromUri.Value = "http://trst";
doc.Save(...);

最后我决定使用XmlDocument:

从头开始创建它。
XmlDocument Request = new XmlDocument();
XmlDeclaration declarationRequest = Request.CreateXmlDeclaration("1.0", "UTF-8", "no");
Request.InsertBefore(declaracionRequest, Request.DocumentElement);
XmlElement soapEnvelope = Request.CreateElement("SOAP-ENVELOPE", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
Request.AppendChild(soapEnvelope);
XmlElement soapHeader = Request.CreateElement("SOAP-ENVELOPE", "Header", Request.DocumentElement.NamespaceURI);
Request.DocumentElement.AppendChild(soapHeader);
XmlElement soapBody = Request.CreateElement("SOAP-ENVELOPE", "Body", Request.DocumentElement.NamespaceURI);
soapBody.SetAttribute("SOAP-ENVELOPE:encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/");
Request.DocumentElement.AppendChild(soapBody);
XmlElement nodeAutorization = Request.CreateElement("Authorization");
XmlElement nodeFromURI = Request.CreateElement("FromURI");
...
soapHeader.AppendChild(nodoAutorization);
nodeAutorization.AppendChild(nodoFromURI);
nodeAutorization.AppendChild(nodoUser);
...

其他的都是一样的。问题是,使用所有元素的代码变得相当大,很难在同一级别生成许多节点。

我不知道是否有更好的做法或更容易的东西,但这是有效的。

如果我正确理解您的问题,您可以使用StringBuilder来创建SOAP信封,然后将该字符串转换为XDocument