开发者

MSXML loadXML won't load elements with namespace prefixes... Why?

开发者 https://www.devze.com 2023-04-10 00:11 出处:网络
Hiho, i guess, it\'s a pretty stupid question, but i had to switch to C/C++ recently and haven\'t done this in years.

Hiho,

i guess, it's a pretty stupid question, but i had to switch to C/C++ recently and haven't done this in years. And right now I'm stuck on the following:

Given XML Element as a simple String:

<myns:factor>1000</myns:factor>

I have to parse the string, add the resulting Element to a surrounding MSXML2 DOM object within the same Namespace.

Right now i try it this way:

  HRESULT hr;

  MSXML2::IX开发者_开发问答MLDOMDocument2Ptr l_xmlFrame;
  MSXML2::IXMLDOMElementPtr l_xmlFrameDoc;

  hr = l_xmlFrame.CreateInstance(__uuidof(MSXML2::DOMDocument));

  if( !FAILED(hr) ) {

    l_xmlFrame->async = VARIANT_FALSE;
    l_xmlFrame->validateOnParse = VARIANT_TRUE;

    // p_strUnit holds the xml as a String
    l_xmlFrame->loadXML(p_strUnit);

  }

The loadXML(...) call just fails , but:

if i remove the namespace declarations and the element looks like this:

<factor>1000</factor>

the call works perfectly!

I really don't understand, why the loadXML function wont parse the string, when the Namespace declarations are set.

Any help appreciated!!!!! :)

Thanks!


The Problem

The string

<myns:factor>1000</myns:factor>

is not well-formed XML (with regard to namespaces). That's why XML parsers generally won't load it.

It's not well-formed because it uses the namespace prefix "myns", which has not been declared.

The Solution

If you changed the XML to something like this, it would parse fine:

<myns:factor xmlns:myns="mynamespaceURI">1000</myns:factor>

The namespace declaration (xmlns:myns="mynamespaceURI") can go on the element where the namespace prefix is used, or any ancestor thereof.

If you can't change the input XML, I would then ask the supplier of the XML, "Why are you giving me broken XML?"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号