如何向 SOAP XML 添加新元素
Posted
技术标签:
【中文标题】如何向 SOAP XML 添加新元素【英文标题】:How to add new elements to a SOAP XML 【发布时间】:2020-10-04 12:14:28 【问题描述】:我有一个 SOAP XML 文件名“LogEvents.xml”,我想从中添加/删除元素。
<?xml version="1.0" encoding="utf-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding" >
<SOAP-ENV:Body xmlns:lle="http://www.examplee.org/logevents" >
<Event>
<eventid>ID-1</eventid>
<title>title1</title>
<description>desc1</description>
<location>
<lat>1.357207</lat>
<long>103.944880</long>
<address>address1</address>
</location>
<datetimestamp>datetime1</datetimestamp>
</Event>
<Event>
<eventid>ID-2</eventid>
<title>title2</title>
<description>desc2</description>
<location>
<lat>1.304121</lat>
<long>103.831950</long>
<address>addres2</address>
</location>
<datetimestamp>datetime2</datetimestamp>
</Event>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
下面显示了我尝试过但使用 Visual Studio 失败的代码。
XDocument xDoc1 = XDocument.Load(@"C:\LogEvents.xml");
xDoc1.Element("SOAP-ENV").Add(new XElement("Event", new XElement("eventid", "strEventID"),
new XElement("title", "title2"),
new XElement("description", "desc3"),
new XElement("location", new XElement("lat", "lat3"),
new XElement("long", "long3"),
new XElement("address", "addresses3")),
new XElement("datetimestamp", "DateTime3")));
我已尝试删除 XML 文件中的 SOAP 信封并将其替换为“事件”并相应地编辑 C# 代码,它的工作原理如下所示。
<?xml version="1.0" encoding="utf-8"?>
<!--Changed to Events-->
<Events>
<Event>
<eventid>ID-1</eventid>
<title>title1</title>
<description>desc1</description>
<location>
<lat>1.357207</lat>
<long>103.944880</long>
<address>address1Edge</address>
</location>
<datetimestamp>datetime1</datetimestamp>
</Event>
<Event>
<eventid>ID-2</eventid>
<title>title2</title>
<description>desc2</description>
<location>
<lat>1.304121</lat>
<long>103.831950</long>
<address>addres2</address>
</location>
<datetimestamp>datetime2</datetimestamp>
<!--Changed to Events-->
</Event>
<Events>
XDocument xDoc1 = XDocument.Load(@"C:\LogEvents.xml");
// Changed SOAP-ENV to Events
xDoc1.Element("Events").Add(new XElement("Event", new XElement("eventid", "ID-3"),
new XElement("title", "title3"),
new XElement("description", "desc3"),
new XElement("location", new XElement("lat", "lat3"),
new XElement("long", "long3"),
new XElement("address", "addresses3")),
new XElement("datetimestamp", "DateTime3")));
有什么方法可以忽略 SOAP 信封,或者有什么方法可以解决它?
【问题讨论】:
【参考方案1】:使用根。需要时,您始终可以从根目录获取默认命名空间。
XDocument xDoc1 = XDocument.Load(FILENAME);
XElement soap = xDoc1.Root;
XNamespace ns = soap.GetDefaultNamespace();
soap.Add(new XElement("Event", new XElement("eventid", "strEventID"),
new XElement("title", "title2"),
new XElement("description", "desc3"),
new XElement("location", new XElement("lat", "lat3"),
new XElement("long", "long3"),
new XElement("address", "addresses3")),
new XElement("datetimestamp", "DateTime3")));
【讨论】:
以上是关于如何向 SOAP XML 添加新元素的主要内容,如果未能解决你的问题,请参考以下文章