简体   繁体   English

我的xml有什么问题?

[英]What's wrong with my xml?

i have the following xml: 我有以下xml:

<messageContent xmlns="http://tempuri.org/" >
<Message type="MappedMessage" >
<Properties RequestId="Point-CurveRequest-8326ad44-a1cd-4a96-b4ef-1c4ad213d940"  Action="getParCurves"  EESId="EESID:NY:20100128:BASE"  Currency="USD"  Index="INX" />
<Body></Body>
</Message>
</messageContent>

and then i have this query: 然后我有这个查询:

var messageType = xmlDoc.SelectSingleNode("/messageContent/Message[@type]");

but no matter what i've tried, i was never able to get the node that i'm looking for. 但是,无论我尝试了什么,我都无法获得想要的节点。 Basically i'm just try to see if there is a node (named "Message") which has a "type" property inside of it. 基本上,我只是尝试看看是否有一个节点(名为“消息”),其中具有“类型”属性。

Has anyone have any idea here? 有人在这里有想法吗?

There's absolutely nothing wrong with your XML - there's something wrong with your XPath expression, though :-) XML绝对没有错-XPath表达式有问题,尽管:-)

Add a XML namespace manager to your code: 将XML名称空间管理器添加到您的代码中:

XmlNamespaceManager mgr = new XmlNamespaceManager(xdoc.NameTable);
mgr.AddNamespace("ns", "http://tempuri.org/");

and then use that namespace manager when you do your SelectSingleNode : 然后在执行SelectSingleNode时使用该名称空间管理器:

var messageType = xdoc.SelectSingleNode("/ns:messageContent/ns:Message[@type]", mgr);

That should work. 那应该工作。

您似乎需要在xpath上建立名称空间上下文,或者摆脱该xmlns =“ http://tempuri.org/”。

NOt a straight forward but will work 不要直截了当,但会起作用

XMLElement messageElement = (XMLElement) xmlDoc.SelectSingleNode("/messageContent/Message");
if(messageElement.HasAttribute("type"))

But the thing is if you have a node Message butdoes not contain type attribute then its not proper format of an xml.Rather i would suggest to check the content of the type attribute like below 但是问题是,如果您有一个节点Message但不包含type属性,那么它的xml格式不正确,而是建议您检查type属性的内容,如下所示

XMLNode messageElement = xmlDoc.SelectSingleNode("/messageContent/Message[@type='MappedMessage']");
if(messageElement != null)
{
//Do SOmething
}

如果messageContent根节点应忽略它想: /Message[@type]或者,如果你想检查文档的整个层次: //Message[@type]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM