โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Error deserializing XML in C#

Here is my code for deserialization in C#:

private void button1_Click(object sender, EventArgs e)
    {
        LandXML myObject;
        XmlSerializer mySerializer =
        new XmlSerializer(typeof(LandXML));
        FileStream myFileStream =
        new FileStream("Nova 6.xml", FileMode.Open);
        myObject = (LandXML)
        mySerializer.Deserialize(myFileStream);
    }

I've generated classes from link http://www.landxml.org/schema/LandXML-1.2/LandXML-1.2.xsd using Visual Studio's tool xsd.exe. I have some generic file based on LandXML Schema (XSD and that XML file are checked for compatibility at http://www.utilities-online.info/xsdvalidation/#.VtBcNeaT6YA, and they are compatible). The thing is that my code never get further than:

XmlSerializer mySerializer =
    new XmlSerializer(typeof(LandXML));

and I get an error (this is only a part of error trace)

'TunnelCore.Utilities.LandXML12.LandXML'. System.InvalidOperationException: There was an error reflecting type 'TunnelCore.Utilities.LandXML12.LandXML'. ---> System.InvalidOperationException: There was an error reflecting property 'Items'. ---> System.InvalidOperationException: There was an error reflecting type 'TunnelCore.Utilities.LandXML12.PlanFeatures'. ---> System.InvalidOperationException: There was an error reflecting property 'PlanFeature'. ---> System.InvalidOperationException: There was an error reflecting type 'TunnelCore.Utilities.LandXML12.PlanFeature'. ---> System.InvalidOperationException: There was an error reflecting property 'Items'. ---> System.InvalidOperationException: There was an error reflecting type 'TunnelCore.Utilities.LandXML12.CoordGeom'. ---> System.InvalidOperationException: There was an error reflecting property 'Items'. ---> System.InvalidOperationException: There was an error reflecting type 'TunnelCore.Utilities.LandXML12.IrregularLine'. ---> System.InvalidOperationException: There was an error reflecting property 'Item'. ---> System.InvalidOperationException: The type for XmlElement may not be specified for primitive types. at System.Xml.Serialization.XmlReflectionImporter.ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, String ns, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) --- End of inner exception stack trace --- at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)

I'm new at programming, but I think that this part is maybe crucial:

...System.InvalidOperationException: The type for XmlElement may not be specified for primitive types.

Can someone, please, help to parse and create this classes correctly. Sample XML files for testing can be found at:

http://landxml.org/schema/LandXML-1.1/samples/TopoCAD/Alignments%20and%20length%20table.xml

XML Reading with several data after "Name"

Here is the xml

<?xml version="1.0"?>
<CFaveDefn-v000 Description="Favourite definitions, Default group" Created="18-Apr-2024 14:49">
    <Defn>
        <Display m_display.contrast.bEnabled="true" m_display.contrast.nLow="-138" m_display.contrast.nHigh="-80" m_display.scale.bEnabled="true" m_display.scale.nLow="-151" m_display.scale.nHigh="-42" m_display.bEnabled="true" m_display.bSmallIcon="true" m_display.n64FreqLow="2801644" m_display.nBandwidth="63913" />
        <Radio m_radio.bEnabled="false" m_radio.n64FreqLow="2801644" m_radio.nBandwidth="63913" />
        <Flags m_flags.bDefault="false" />
        <Name m_name.strGroup="-- UNKNOWN" m_name.strFolder="MIL-STD 188-141 - ALE" m_name.strTitle="2.835,000 ALE LSB unk-tx TIS:K01 TO:K13 +110" />
        <RX m_rx.nActive="0" m_rx.anEnabled="1" m_rx.astrDemod_count="1" m_rx.astrDemod_value_0="&lt;CDSPDemodRX-v000>&lt;Audio m_audio.bASIO=&quot;false&quot; m_audio.bEnable=&quot;true&quot; m_audio.nLevel=&quot;100&quot; m_audio.nDevice=&quot;-1&quot; m_audio.nChannels=&quot;0&quot; m_audio.szDevice=&quot;Default&quot;/>&lt;Freq m_freq.n64RX=&quot;2835000&quot; m_freq.n64TX=&quot;10000000&quot; m_freq.n64RXOffset=&quot;0&quot;/>&lt;Mode m_mode.nMode=&quot;0&quot;/>&lt;Main m_main.nID=&quot;0&quot; m_main.bTX=&quot;false&quot; m_main.bLock_0=&quot;false&quot;/>&lt;Filter m_filter.nLow=&quot;100&quot; m_filter.nHigh=&quot;2700&quot; m_filter.nTaps=&quot;257&quot; m_filter.nWindowing=&quot;3&quot;/>&lt;AGC m_agc.nAGC=&quot;1&quot; m_agc.levels_0.nDecay=&quot;0&quot; m_agc.levels_0.nGain=&quot;40&quot; m_agc.levels_0.nHang=&quot;0&quot; m_agc.levels_0.nKnee=&quot;0&quot; m_agc.levels_0.nSlope=&quot;0&quot; m_agc.levels_1.nDecay=&quot;250&quot; m_agc.levels_1.nGain=&quot;0&quot; m_agc.levels_1.nHang=&quot;100&quot; m_agc.levels_1.nKnee=&quot;-130&quot; m_agc.levels_1.nSlope=&quot;6&quot; m_agc.levels_2.nDecay=&quot;500&quot; m_agc.levels_2.nGain=&quot;0&quot; m_agc.levels_2.nHang=&quot;250&quot; m_agc.levels_2.nKnee=&quot;-130&quot; m_agc.levels_2.nSlope=&quot;6&quot; m_agc.levels_3.nDecay=&quot;1000&quot; m_agc.levels_3.nGain=&quot;0&quot; m_agc.levels_3.nHang=&quot;500&quot; m_agc.levels_3.nKnee=&quot;-130&quot; m_agc.levels_3.nSlope=&quot;6&quot;/>&lt;CW m_cw.bEnable=&quot;false&quot; m_cw.nLevel=&quot;48&quot;/>&lt;NB m_nb.bEnable=&quot;false&quot; m_nb.nThreshold=&quot;50&quot; m_nb.nWidth=&quot;50&quot;/>&lt;NR m_nr.bEnable=&quot;false&quot; m_nr.nMethod=&quot;0&quot; m_nr.nLMSThreshold=&quot;50&quot; m_nr.nRRNoise1=&quot;5&quot; m_nr.nLMSWidth=&quot;50&quot; m_nr.nLMSLevel=&quot;10&quot; m_nr.nSpectralReduction_0=&quot;3&quot; m_nr.nSpectralThreshold_0=&quot;10&quot; m_nr.nSpectralRescale_0=&quot;2&quot; m_nr.cleanup.nBins=&quot;0&quot; m_nr.cleanup.nMultiply=&quot;0&quot; m_nr.cleanup.nSquelch=&quot;0&quot; m_nr.cleanup.nLevel=&quot;0&quot; m_nr.cleanup.nWidth=&quot;0&quot; m_nr.cleanup.bPCS=&quot;0&quot; m_nr.cleanup.bSquelch=&quot;0&quot;/>&lt;Notch m_notch.bEnable=&quot;false&quot; m_notch.nLevel=&quot;50&quot;/>&lt;Squelch m_squelch.fm.hWnd=&quot;69082&quot; m_squelch.fm.nMsg=&quot;50078&quot; m_squelch.fm.bAuto=&quot;false&quot; m_squelch.fm.bCTCSS=&quot;false&quot; m_squelch.fm.bEnable=&quot;false&quot; m_squelch.fm.nCTCSSTone=&quot;67000&quot; m_squelch.fm.nCTCSSLevel=&quot;5&quot; m_squelch.fm.nLevel=&quot;2&quot; m_squelch.vad.bEnable=&quot;false&quot; m_squelch.vad.nCache=&quot;25&quot; m_squelch.vad.nLevel=&quot;25&quot; m_squelch.vad.nHang=&quot;250&quot;/>&lt;/CDSPDemodRX-v000>" />
        <TX m_tx.strMod="" />
    </Defn>
</CFaveDefn-v000>

I have a xml document with several data under the name "RX". So far i can only read the first name in "RX" that is "m_rx.nActive" which is value "0".

I need to read 2 data:

  • Freq m_freq.n64RX="2835000" 'i need the 2835000 value
  • Mode m_mode.nMode="0" 'i need the "0" in "0&quot"

Can you help me please to resolve this problem ?

Many thanks Raimund

Dim xmlToTxt As XmlReader = XmlReader.Create(filename) '

    Do While xmlToTxt.Read()

        If xmlToTxt.NodeType = XmlNodeType.Element AndAlso xmlToTxt.Name = "RX" Then

            MsgBox(xmlToTxt.GetAttribute(0) & "   <>")  'm_rx.nActivate="0" i can read

        End If

    Loop

org.apache.fop.fo.extensions.svg.SVGElement.getDimension Could not set base URL for svg

I am trying to implement SVG inside an instream-foreign-object below is the code snip it; this is a code section from a XSLT (1.0);

<xsl:template name="Draft">
    <fo:block-container>
        <fo:block>
            <fo:instream-foreign-object>
                <svg:svg xmlns:svg="http://www.w3.org/2000/svg" xml:base="http://example.org/today/" >
                    <svg:defs>
                        <svg:font-face font-family="sample">
                            <svg:font-face-src>
                                <svg:font-face-uri href="sample.ttf"/>
                            </svg:font-face-src>
                        </svg:font-face>
                    </svg:defs>
                    <svg:text>
                        DRAFT
                    </svg:text>
                </svg:svg>
            </fo:instream-foreign-object>
        </fo:block>
    </fo:block-container>
</xsl:template>

now when I am trying to convert from xml to pdf it is giving me below error:

org.apache.fop.fo.extensions.svg.SVGElement.getDimension Could not set base URL for svg
        java.lang.IllegalArgumentException: URI is not absolute
                at java.base/java.net.URL.fromURI(URL.java:721)
                at java.base/java.net.URI.toURL(URI.java:1139)
                at org.apache.fop.fo.extensions.svg.SVGElement.getDimension(SVGElement.java:77)
.
.
.

So can you please help me to understand why we are seeing this error?

How to run tests concurrently but execute classes within each test sequentially using TestNG XML configuration?

I want to configure my TestNG XML file to achieve concurrent execution of tests while ensuring that the classes within each test run sequentially. Currently, I have set the parallel attribute to true for the suite, enabling concurrent execution of tests. However, I have set the parallel attribute to false for each individual test to ensure sequential execution of classes within each test.

`

<test name="Panel Tests - Part 1" parallel="false" thread-count="1">
    <!-- Test configurations -->
</test>

<test name="Panel Tests - Part 2" parallel="false" thread-count="1">
    <!-- Test configurations -->
</test>

<!-- Other tests -->
`

Despite this configuration, the tests are not running concurrently. Could someone please advise on how to correctly configure TestNG to achieve concurrent execution of tests while ensuring sequential execution of classes within each test?

Correctly expanding xml namespaces without defined end character into valid URIs

As far as I know, the semantic web consists of triples of URIs. Namespace shorthands are widely used to abbreviate them in daily use. I thought, namespace shorthands would be expanded to URIs by simple concatenation, e.g. the famous dc:title in the well-known dc: namespace (which is defined as http://purl.org/dc/elements/1.1/, note that the last character is a /) would be expanded to, and hence be semantically equal to http://purl.org/dc/elements/1.1/title.

Then I came over some namespace definitions which lack a sensible separation character at their end. Some examples from http://live.dbpedia.org/sparql?nsdecl

and some from the Most common RDF namespaces list:

How to expand such namespaces into valid linked data URIs?

The W3C Recommendation Namespaces in XML defines:

An expanded name is a pair consisting of a namespace name and a local name.

And Fredrik Lundh writes on effbot.org:

In an Element tree, qualified names are stored as universal names in Clarkโ€™s notation, which combines the URI and the local part into a single string, given as โ€˜{uri}localโ€™.

This may be suitable for a wide range of use cases, but it doesnโ€™t conform to the idea that linked data constists of URIs, which cannot start with a {.

I would have thought that xsd:element should not be expanded to http://www.w3.org/2001/XMLSchemaelement in linked data (nor to {http://www.w3.org/2001/XMLSchema}element), should it? How must this be implemented correctly?

How to remove unused > character in xml string in c#

I have to remove some special characters and ">" in XML string. Load XML throwing Data root level error.

public T ConvertXmlFromByte<T>(byte[] data)
{
    T model = null;
    try
    {
        if (data != null)
        {
            XmlDocument xmlDoc = null;
            XmlSerializer serializer = null;
            string xml = "";
            xmlDoc = new XmlDocument();
            xml = Encoding.UTF8.GetString(data);
            //xml = Regex.Replace(xml, @"[^&;:()a-zA-Z0-9\=./><_-~-]", string.Empty);
            xmlDoc.LoadXml(xml);
        }
    }
    catch (Exception ex)
    {
        _customLogger.Error(ex.Message, ex);
    }
    return model;
}

Below is my XML string:

<?xml version="1.0" encoding="utf-8" standalone="no"?><Test xmlns="https://cdn.Test.go.cr/xml-schemas/v4.3/test" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   </Test>>

java XML transformer showing veracode 611 improper restriction of XML external entity reference

I am continuously getting the CVE 611 improper restriction of XML external entity reference error on Veracode with the following javax.xml.tranformer code. I have consulted other questions on this forum and tried those options but they do not seem to be resolving the code scan. Any helpful insights would be greatly appreciated.

TransformerFactor factory = TransformerFactory.newInstance();  //defaultInsance()
factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA,  false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, false);
factory.setAttribute(XMLConstants.SUPPORT_DTD, false);
factory.setAttribute(XMLConstants.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://xml.org/sax/features/nonvalidating/load-external-dtd", false);
Transformer transformer = factory.newTransformer();

transformer.transform(new DOMSource(node), new StreamResult(writer));  //valid node and writer instances

android - button not getting centered vertically

After I run this it displays this on the top not the center. But in xml preview it's centered .

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center_vertical"
    tools:context=".MainActivity"

    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/_1"
        android:textSize="25sp"
        android:layout_gravity="center"
        />
    <Button
        android:id="@+id/roll_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/roll"
        android:layout_gravity="center"
        />
</LinearLayout>

what changes it was running fine but after adding Toast it started happening IG.

Inserting XML tags at specific part of file without disrupting format

I'm trying to work with some XML files to do sentence tagging whilst maintaining the original structure of the file. The files look like so:

<text xml:lang="">
    <body>
      <div>
        <p>
          <p>
            <lb xml:id="p1z1" />19.
                    <lb xml:id="p1z2" />esse Christolam meam te adeo candide et humaniter Bullingere colendissime,
                    <lb xml:id="p1z3" />esse epistolam meam interpretatum. Caeterum, quod scribis te ex consilio consanguine
                    <lb xml:id="p1z4" />et affinium generi tui responsum fratri meo coram dedisse, non
                    <lb xml:id="p1z5" />possum satis mirari, qui hoc factum sit. Res enim ista ad me suum ad
                    <lb xml:id="p1z6" />fratrem pertinebat. Nec ita fueram abs te dimissus, quod vel tu tale
                    <lb xml:id="p1z7" />quid reciperes vel ego probarem, sed ita tua sponte pollicebaris vel te,
                    <lb xml:id="p1z8" />vel generum mihi per literas responsurum. Frater igitur dixit quidem
                    <lb xml:id="p1z9" />mihi te in praesentia nescio quorum (qui namque fuerint excidit) voluisse
                    <lb xml:id="p1z10" />respondere se vero voluisse recipere, imo admonuisse te ut, quemadmodum
                    <lb xml:id="p1z11" />promisisses, ita faceres. Ego simulatque tergiversationem istam cognoscere
                    <lb xml:id="p1z12" />non potui aliter interpretari quam ali fortassis aliquid monstri,
                    <lb xml:id="p1z13" />ut dicitur. Nam quae plana sunt et integra sive dicantur sive scripsisse
                    <lb xml:id="p1z14" />nihil refert. Utut sit, ego iniuriam illam, ex qua omnes istae
                    <lb xml:id="p1z15" />difficultates sunt ortae, iampridem domino deque commendavi, qui
                    <lb xml:id="p1z16" />per Mosen. Mea est ultro et ego retribuam eis in tempore.
                    <lb xml:id="p1z17" />De altero etiam capite accipio tuam excusationem. Quum enim tam sancte
                    <lb xml:id="p1z18" />affirmes te semper erga nos non aliter quam bene et fuisse et
...
...
...
        </p>
      </div>
    </body>
  </text>
</TEI>

The sentences I need to tag span over several lines. The lines are tagged with the line break tag "<lb xml:id="n" />". I need to somehow tag the sentences, and then append them back with their original formal to the file. The issue I encounter is that while the text contains newline characters, as soon as I create an instance of a sentence and try to append to the line break tag, the new line character isn't valid....

The output should look like:

<text xml:lang="">
    <body>
      <div>
        <p>
          <p>
            <lb xml:id="p1z1" /><s n="1" xml:lang="la">19.</s>
                    <lb xml:id="p1z2" /><s n="1" xml:lang="la">esse Christolam meam te adeo candide et humaniter Bullingere colendissime,
                    <lb xml:id="p1z3" />esse epistolam meam interpretatum.</s><s n="2" xml:lang="la"> Caeterum, quod scribis te ex consilio consanguine
                    <lb xml:id="p1z4" />et affinium generi tui responsum fratri meo coram dedisse, non
                    <lb xml:id="p1z5" />possum satis mirari, qui hoc factum sit.</s><s n="3" xml:lang="la"> Res enim ista ad me suum ad
                    <lb xml:id="p1z6" />fratrem pertinebat.</s><s n="4" xml:lang="la"> Nec ita fueram abs te dimissus, quod vel tu tale
                    <lb xml:id="p1z7" />quid reciperes vel ego probarem, sed ita tua sponte pollicebaris vel te,
                    <lb xml:id="p1z8" />vel generum mihi per literas responsurum.</s><s n="5" xml:lang="la"> Frater igitur dixit quidem
                    <lb xml:id="p1z9" />mihi te in praesentia nescio quorum (qui namque fuerint excidit) voluisse
                    <lb xml:id="p1z10" />respondere se vero voluisse recipere, imo admonuisse te ut, quemadmodum
                    <lb xml:id="p1z11" />promisisses, ita faceres.</s><s n="6" xml:lang="la"> Ego simulatque tergiversationem istam cognoscere
                    <lb xml:id="p1z12" />non potui aliter interpretari quam ali fortassis aliquid monstri,
                    <lb xml:id="p1z13" />ut dicitur.</s><s n="7" xml:lang="la"> Nam quae plana sunt et integra sive dicantur sive scripsisse
                    <lb xml:id="p1z14" />nihil refert.</s><s n="8" xml:lang="la"> Utut sit, ego iniuriam illam, ex qua omnes istae
                    <lb xml:id="p1z15" />difficultates sunt ortae, iampridem domino deque commendavi, qui
                    <lb xml:id="p1z16" />per Mosen.</s><s n="9" xml:lang="la"> Mea est ultro et ego retribuam eis in tempore.</s>
                    <lb xml:id="p1z17" /><s n="10" xml:lang="la">De altero etiam capite accipio tuam excusationem.</s><s n="11" xml:lang="la"> Quum enim tam sancte
                    <lb xml:id="p1z18" />affirmes te semper erga nos non aliter quam bene et fuisse et
...
...
...
       </p>
      </div>
    </body>
  </text>
</TEI>

My code looks like:

import xml.etree.ElementTree as ET
from nltk.tokenize import sent_tokenize
import nltk

# Ensure NLTK's sentence tokenizer is available
nltk.download('punkt')

def remove_ns_prefix(tree):
    for elem in tree.iter():
        if '}' in elem.tag:
            elem.tag = elem.tag.split('}', 1)[1]  # Removing namespace
    return tree

def process_file(input_xml, output_xml):
    tree = ET.parse(input_xml)
    root = remove_ns_prefix(tree.getroot())

    for body in root.findall('.//body'):
        for paragraph in body.findall('.//p'):
            # Extract all lb elements and following texts
            lb_elements = list(paragraph.findall('.//lb'))
            lb_ids = [lb.attrib.get('xml:id', '') for lb in lb_elements]  # Store lb ids
            text_after_lb = [(lb.tail if lb.tail else '') for lb in lb_elements]
            
            # Combine the text and tokenize into sentences
            entire_text = ' '.join(text_after_lb)
            sentences = sent_tokenize(entire_text)
            sentences2 = " ".join(sentences).split("\n")
            print(sentences2)
            
            # Clear the paragraph's existing content
            paragraph.clear()

            # Pair up lb tags and sentences using zip, reinsert them into the paragraph
            for lb_id, sentence in zip(lb_ids, sentences):
                # Reinsert lb element
                lb_attrib = {'xml:id': lb_id} if lb_id else {}
                new_lb = ET.SubElement(paragraph, 'lb', attrib=lb_attrib)
                # Attach sentence to this lb
                if sentence:
                    sentence_elem = ET.SubElement(paragraph, 's', attrib={'xml:lang': 'la'})
                    sentence_elem.text = sentence

    # Write the modified tree to a new file
    tree.write(output_xml, encoding='utf-8', xml_declaration=True, method='xml')

I'm losing my mind. Hopefully I have an XML pro who is willing to come to my rescue.

I've also tried first tagging, and then reinserting the line break tags afterwards, but due to the nature of XML it's tough. The next thing I would maybe attempt is to create temporary .txt files and go line by line and insert the tags on the lines that don't match...

Any and all help appreciated at this point.

Unable to sign SoapMessage in C#

I want to sign a xml with every time i got a message: Invalid Reference-element on the line: signedXml.ComputeSignature(); If i sign with URI="" then i have no errors. But if i specifiy an id i have. Can someone help me?

I tried this code:

public static void SignSoapMessage(XmlDocument soapEnvelope, X509Certificate2 certificate, Excel.Workbook wbTest)

        RSA privateKey = certificate.GetRSAPrivateKey();
        // Create a SignedXml object
        SignedXml signedXml = new SignedXml(soapEnvelope);

        // Assign the key to the SignedXml object.
        signedXml.SigningKey = privateKey;

        // Create a reference to be signed.
        System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference();
        reference.Uri = "#id-2832";

        // Add the reference to the SignedXml object
        signedXml.AddReference(reference);

        KeyInfo keyInfo = new KeyInfo();
        KeyInfoX509Data keyInfoData = new KeyInfoX509Data();
        keyInfo.AddClause(keyInfoData);
        signedXml.KeyInfo = keyInfo;

        // Add transforms 
        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        reference.AddTransform(new XmlDsigC14NTransform());

        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // Specify the digest algorithm

        signedXml.ComputeSignature();
        XmlElement signatureElement = signedXml.GetXml();
        soapEnvelope.DocumentElement.AppendChild(signatureElement);

    private string GenerateSOAPRequest(string xbrlDocument, string binarySecurityToken, X509Certificate2 certificate)
    {

        string publicKey = Convert.ToBase64String(certificate.GetPublicKey());


        string soapEnvelope = $@"<?xml version=""1.0"" encoding=""UTF-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ns=""http://logius.nl/digipoort/koppelvlakservices/1.2/"" xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"" xmlns:wsu=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"">
    <soapenv:Header wsu:Id=""header-id"" xmlns:wsa=""http://www.w3.org/2005/08/addressing"">
        <wsse:Security>
                {binarySecurityToken}
            <!-- Add Timestamp -->
            <wsu:Timestamp wsu:Id=""timestamp-id"">
                <wsu:Created>{DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")}</wsu:Created>
                    <wsu:Expires>{DateTime.UtcNow.AddMinutes(5).ToString("yyyy-MM-ddTHH:mm:ssZ")}</wsu:Expires>
            </wsu:Timestamp>
        </wsse:Security>
        <wsa:Action wsu:Id=""id-2831"">http://logius.nl/digipoort/wus/2.0/aanleverservice/1.2/AanleverService/aanleverenRequest</wsa:Action>
        <wsa:ReplyTo wsu:Id=""id-2832"">
            <wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>
        </wsa:ReplyTo>
        <wsa:MessageID wsu:Id=""id-2830"">uuid:0a528087-4b2e-4d89-ba5d-a0168b344f04</wsa:MessageID>
        <wsa:To wsu:Id=""id-2829"">https://preprod-dgp.procesinfrastructuur.nl/wus/2.0/aanleverservice/1.2</wsa:To>
    </soapenv:Header>
    <soapenv:Body wsu:Id=""id-2828"">
        <ns:aanleverRequest xmlns:ns=""http://logius.nl/digipoort/koppelvlakservices/1.2/"">
            <ns:berichtsoort>Jaarrekening</ns:berichtsoort>
            <ns:aanleverkenmerk>{KVKnummer}_{EindDatumGeconverteerd}</ns:aanleverkenmerk>
            <ns:identiteitBelanghebbende>
                <ns:nummer>{KVKnummer}</ns:nummer>
                <ns:type>KvK</ns:type>
            </ns:identiteitBelanghebbende>
            <ns:rolBelanghebbende>Intermediair</ns:rolBelanghebbende>
            <ns:berichtInhoud>
                <ns:mimeType>application/xml</ns:mimeType>
                <ns:bestandsnaam>{KVKnummer}_{EindDatumGeconverteerd}.xbrl</ns:bestandsnaam>
                <ns:inhoud>{Convert.ToBase64String(Encoding.UTF8.GetBytes(xbrlDocument))}</ns:inhoud>
            </ns:berichtInhoud>
        </ns:aanleverRequest>
    </soapenv:Body>
</soapenv:Envelope>";

        return soapEnvelope;
    }

unexpected result using lxml remove

I have a XML and need to remove a few types of tags. I used the iter method to check each element. I noticed if there is a nested element its child is also deleted. The following tag will not be deleted. For example as follows, the tag delete2 is a child of delete1 and both will be removed. The tag section can't be deleted for some reason. Is this a bug? Or did I miss something? Thanks.

# %%
from lxml import etree

# unexpected output when nested elements are deleted
xml_str = """
<spdoc>
  <commentary>
    <body>
      <delete1>
        <delete2>
        </delete2>
      </delete1>
      <section name="delete">
      </section>
    </body>
  </commentary>
</spdoc>
"""

root = etree.fromstring(xml_str)
for element in root.iter():
    is_remove = False
    if element.tag == "delete1":
        is_remove = True
    if element.tag == "delete2":
        is_remove = True
    if element.tag == "section" and element.attrib.get("name") == "delete":
        is_remove = True
    print(f"{element} {is_remove}")
    if is_remove:
        element.getparent().remove(element)

print(etree.tostring(root, encoding="utf-8").decode("utf-8"))

the unexpected output is :

<Element spdoc at 0x103489680> False
<Element commentary at 0x103489640> False
<Element body at 0x1034b5540> False
<Element delete1 at 0x1037eb700> True
<Element delete2 at 0x1037eba40> True
<spdoc>
    <commentary>
        <body>
            <section name="delete">
            </section>
        </body>
    </commentary>
</spdoc>

To print the data after replacing the given expression with the values in XML file using "ElementTree" library

Given XML file snippet is:

<?xml version="1.0" standalone="yes"?>
<event_configuration family="21" version="2">
    <pqr subtype="abc">
    <event val="73002" name="$MyCpu"> </event>
    <event val="73003" name="$MyCpuKernel"> </event>

    <metric name="Ratio" expression="$MyCpuKernel / $MyCpu"> </metric>
    </pqr>
</event_configuration>

I have parsed this xml file using "ElementTree" library in Python, please find the code below:

    def parse_xml_to_json(self):
        data = {'metric': []}
        root = ET.fromstring(self.xml_file)

        for element in root.findall('.//*'):
            element_type = element.tag
            if element_type not in ["pqr", "stu", "vwx"]:
                continue
            subtype_name = element.attrib['subtype']
            event_map = {}
            for event in element.findall('.//event'):
                event_name = event.attrib['name']
                val_value = event.attrib['val']
                event_map[event_name] = val_value

            for metric in element.findall('metric'):
                expression = metric.attrib['expression']
                metric_name = metric.attrib['name']
          
                for event_name, val_value in event_map.items():
                    expression = expression.replace(event_name, val_value)

                data['metric'].append({
                    'Name': metric_name,
                    'Expression': expression,
                    'Type': element_type
                })

        return data

I am getting the output, but this code is unable to replace the event name present inside "Expression" with the val_value as shown below:-

Output:

{
"metric": [
    {
        "Name": "Ratio",
        "Expression": "73002Kernel / 73002",
        "Type": "pqr"
    },
    ....
    ....
]
}
    

Here, we can see in the "Expression" it should print "73003 / 73002". I am unable to think of how to solve this issue. Is it possible to use regex here, how to apply it? Please suggest.

Spring Boot XML Header and Version Tag

I am returning text/xml responses in my spring boot application. However, there are two key issues that cannot be recoverable on the client side (since we are not authorized to make any change on the client):

1 - The first issue is: My responses do not include

<?xml version="1.0" encoding="utf-8"?>
.

How can I add this ?

2 - The second one is: Content-Length header is missing in my responses. How can I include this ?

Thank you for your valuable ideas.

โŒ
โŒ