문제

Trying to get such output

<DeclarationFile>
<Declaration Id="DEC">
<DokPVNv4>
<ParskMen>5</ParskMen>
<ParskCeturksnis xsi:nil="true"/>

Can not create <ParskCeturksnis xsi:nil="true"/>

If use just

$ParskCeturksnis = new SimpleXMLElement("<ParskCeturksnis></ParskCeturksnis>");
$ParskCeturksnis->addAttribute("xsi:nil", "true", "http://www.w3.org/2001/XMLSchema-instance"); 
echo $ParskCeturksnis->asXml();

all works

But if whole code

$DOM = new DOMDocument('1.0','UTF-8');

$DeclarationFile = $DOM->createElement('DeclarationFile');
$DOM->appendChild($DeclarationFile);

$Declaration = $DOM->createElement('Declaration');
$DeclarationFile->appendChild($Declaration);
$Declaration_att = $DOM->createAttribute('Id');
$Declaration->appendChild($Declaration_att);
$att_Declaration_text = $DOM->createTextNode('DEC');
$Declaration_att->appendChild($att_Declaration_text);

$DokPVNv4 = $DOM->createElement('DokPVNv4');
$Declaration->appendChild($DokPVNv4);

$ParskMen = '5';
$ParskMen = $DOM->createElement('ParskMen',mb_convert_encoding($ParskMen, "UTF-8") );
$DokPVNv4->appendChild($ParskMen);

$ParskCeturksnis = new SimpleXMLElement("<ParskCeturksnis></ParskCeturksnis>");
$ParskCeturksnis->addAttribute("xsi:nil", "true", "http://www.w3.org/2001/XMLSchema-instance"); 
echo $ParskCeturksnis->asXml();

echo $DOM->saveXML(); 

get error XML Parsing Error: junk after document element

Searched google, but have not found solution....

Tried

 $ParskCeturksnis = $DOM->createElement('ParskCeturksnis');
 $DokPVNv4->appendChild($ParskCeturksnis)->addAttribute("xsi:nil", "true", "http://www.w3.org/2001/XMLSchema-instance");

get XML Parsing Error: no element found

도움이 되었습니까?

해결책

You seem to be confusing the SimpleXML and DOM extensions. While they are both implemented on top of the same parser, and can be switched between easily using dom_import_simplexml() and simplexml_import_dom(), that doesn't mean you can simply call methods which work on one on objects created by the other.

In your case, you are primarily using the DOM, so you need to add your attribute using the appropriate DOM functions, specifically ->createAttributeNS() and ->appendChild().

I think the code you need is this:

$ParskCeturksnis = $DOM->createElement('ParskCeturksnis');
$ParskCeturksnis->appendChild($DOM->createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil"));
$DokPVNv4->appendChild($ParskCeturksnis);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top